一开始是用string数组做,但是只能做一位加法,多位就不好判断字符串,所以改用数组存储数字,再计算。
- 分别用a b数组存储输入的字符串中的数字
- 用sum数组存储每一位的加和,注意,最好是逆序存储和,这样如果有进位可以存储在sum[count+1],不会出现下溢
- 对sum数组处理进位(知道十进制进位的方法,只要把10改成sushu[i]即可
- 逆序输出sum数组即可
#include <algorithm> #include <cstring> #include <iostream> using namespace std; int sushu[25] = {2,3,5,7,11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; //素数数组 int main() { int a[26],b[26];//存数 int sum[26]; //存和 char c; int i,j; int alen,blen; //三个数组初始化 memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); memset(sum, 0, sizeof(sum)); //输入a b for (i = 0; ; ){ scanf("%d%c",&a[i],&c); if (c == ' ') break; else i++; } alen = i; for (i = 0; ; ){ scanf("%d%c",&b[i],&c); if (c == '\n') break; else i++; } blen = i; for (j = 0,i = alen; i >=0; i--,j++){ sum[j] += a[i]; } for (j = 0,i = blen; i >= 0; i--,j++){ sum[j] += b[i]; } int count = alen>blen?alen:blen; //进位 for (int i = 0,j = 0; i <= count; i++,j++){ if (sum[i] >= sushu[j]) sum[i+1] += sum[i]/sushu[j]; sum[i] %= sushu[j]; if (sum[count+1]) count++; } //输出 for (int i = count; i > 0; i--){ cout<<sum[i]<<","; } cout<<sum[0]; } // 64 位输出请用 printf("%lld")