解题思路:
因为一半的类型长度已经不够题目要求了,所以我们要使用字符串来考虑:
首先把两个数分别读入两个字符串(str1,str2);接着把这两个字符串反序放到整型数组中(注意减'0');
然后对应相加,这里要注意进位,并且进位最大为1不可能超过1(9+9=18);和我们小学普通加法一样,置不过位数有点多让计算机来计算而已;
11233 + 2356 = ?
1 1 2 3 3
2 3 5 6
---------------
1 3 5 8 9
注意是重后向前加的。
注意事项:
参考代码:
#include <cstdio> #include <cstring> #include <string> #include <cmath> #include <iostream> #include <algorithm> using namespace std; int a[1001], b[1001], c[1001]; char str1[1001], str2[1001]; int main() { int len_str1, len_str2, len_max, k = 0; scanf("%s%s", str1, str2); len_str1 = strlen(str1); for(int i = 0, j = len_str1 - 1; j >= 0; ++i, --j) { a[i] = str1[j] -'0'; } len_str2 = strlen(str2); for(int i = 0, j = len_str2 - 1; j >= 0; ++i, --j) { b[i] = str2[j] -'0'; } len_max = len_str1 > len_str2 ? len_str1 : len_str2; for(int i = 0; i < len_max; ++i) { c[i] = (a[i]+b[i]+k)%10; k = (a[i]+b[i]+k)/10; } if(k) { c[len_max] = 1; printf("%d",1); } for(int i=len_max-1;i>=0;--i) { printf("%d",c[i]); } printf("\n"); return 0; }
0.0分
2 人评分