SDNU 1372.Problem C:Primary Arithmetic(高精度)
Description
Children are taught to add multi-digit numbers from right-to-left one digit at a time. Many find the "carry" operation - in which a 1 is carried from one digit position to be added to the next - to be a significant challenge. Your job is to count the number of carry operations for each of a set of addition problems so that educators may assess their difficulty.
Input
Each line of input contains two unsigned integers less than 10 digits. The last line of input contains 0 0.
Output
For each line of input except the last you should compute and print the number of carry operations that would result from adding the two numbers, in the format shown below.
Sample Input
123 456 555 555 123 594 0 0
Sample Output
No carry operation. 3 carry operations. 1 carry operation.
Source
思路:忘了初始化,让我wa了好多次。
#include <cstdio> #include <iostream> #include <cmath> #include <string> #include <cstring> #include <algorithm> #include <queue> #include <vector> #include <map> using namespace std; #define ll long long const int inf = 0x3f3f3f3f; const int mod = 1e9+7; char s1[18], s2[18], ads[1000+8]; int n, m, sum; void additive(char* a, char* b) { // memset(ads, 0, sizeof(ads)); int len, len1, len2; int ad[100]; len1 = strlen(a); len2 = strlen(b); if(len1 == len2) len = len1; else if(len1>len2)///短的数字位不足。将数字往后移,前面补“0”,便于计算 { len = len1; for(int i = len; i >= len-len2; i--) b[i] = b[i-len+len2]; for(int i = len-len2-1; i >= 0; i--) b[i] = '0'; } else if(len1<len2)///短的数字位不足。将数字往后移,前面补“0”,便于计算 { len = len2; for(int i = len; i >= len-len1; i--) a[i] = a[i-len+len1]; for(int i = len-len1-1; i >= 0; i--) a[i] = '0'; } int t = 0; for(int i = len-1; i >= 0; i--)///进行计算 { ad[i] = (a[i]-'0')+(b[i]-'0')+t;///把原本该有的数加上,再加上前一位需要进的“1” t= 0; if(ad[i] >= 10) { t++; sum++; // cout<<sum<<"---"<<endl; ad[i] = ad[i]-10; ads[i] = ad[i]+'0'; } else ads[i] = ad[i]+'0'; } if(t == 1)///如果位数已经变大,就将所有数往后移,再在最前面加一 { for(int i = len; i >= 0; i--) ads[i] = ads[i-1]; ads[0] = '1'; } } int main() { while(~scanf("%d%d", &n, &m) && (n+m)) { int buffer1 = n, buffer2 = m, id1 = 0, id2 = 0; memset(s1, 0, sizeof(s1)); memset(s2, 0, sizeof(s1)); while(buffer1) { id1++; buffer1 /= 10; } while(buffer2) { id2++; buffer2 /= 10; } for(int i = id1-1; i >= 0; i--) { s1[i] = n%10+'0'; n /= 10; } for(int i = id2-1; i >= 0; i--) { s2[i] = m%10+'0'; m /= 10; } // cout<<s1<<endl<<s2<<endl; sum = 0; additive(s1, s2); if(sum == 0)printf("No carry operation.\n"); else if(sum == 1)printf("%d carry operation.\n", sum); else printf("%d carry operations.\n", sum); } return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步