2881 - 【设计型】第11章:指针和数组 高精度加法
输入两个整数a和b,输出这两个整数的和。a和b都不超过100位。
由于a和b都比较大,所以不能直接使用语言中的标准数据类型来存储。对于这种问题,一般使用数组来处理。
定义一个数组A,A[0]用于存储a的个位,A[1]用于存储a的十位,依此类推。同样可以用一个数组B来存储b。
计算c = a + b的时候,首先将A[0]与B[0]相加,如果有进位产生,则把进位(即和的十位数)存入r,把和的个位数存入C[0],即C[0]等于(A[0]+B[0])%10。然后计算A[1]与B[1]相加,这时还应将低位进上来的值r也加起来,即C[1]应该是A[1]、B[1]和r三个数的和.如果又有进位产生,则仍可将新的进位存入到r中,和的个位存到C[1]中。依此类推,即可求出C的所有位。
最后将C输出即可。
Input
输入包括两行,第一行为一个非负整数a,第二行为一个非负整数b。两个整数都不超过100位,两数的最高位都不是0。
Output
输出一行,表示a + b的值。
Examples
Input
20100122201001221234567890 2010012220100122
Output
20100122203011233454668012
Solution C
#include<string.h> #include<stdio.h> int main() { char a[101]; char b[101]; char c[101]; memset(a, '0', sizeof(a)); memset(b, '0', sizeof(b)); memset(c, '0', sizeof(c)); gets(a); gets(b); int i, j; int flag; int d; int temp_1, temp_2 = 0; int len_a, len_b, len_c; len_a = strlen(a); len_b = strlen(b); if(len_a >= len_b) { len_c = len_a; flag = 1; d = len_a - len_b; } else { len_c = len_b; flag = 0; d = len_b - len_a; } if(flag) { for(i = len_c-1; i >= 0; i--) { if(i >= d) { temp_1 = a[i] - '0' + b[i-d] - '0' + temp_2; temp_2 = temp_1 / 10; c[i+1] = temp_1 % 10 + '0'; if(temp_2) { c[i] = temp_2 + '0'; } } else { temp_1 = a[i] - '0' + temp_2; temp_2 = temp_1 / 10; c[i+1] = temp_1 % 10 + '0'; if(temp_2) { c[i] = temp_2 + '0'; } } } } else { for(i = len_c-1; i >= 0; i--) { if(i >= d) { temp_1 = a[i-d] - '0' + b[i] - '0' + temp_2; temp_2 = temp_1 / 10; c[i+1] = temp_1 % 10 + '0'; if(temp_2) { c[i] = temp_2 + '0'; } } else { temp_1 = b[i] - '0' + temp_2; temp_2 = temp_1 / 10; c[i+1] = temp_1 % 10 + '0'; if(temp_2) { c[i] = temp_2 + '0'; } } } } for(i = 0; i <= len_c; i++) { if(i == 0 && c[i] == '0') { continue; } printf("%c", c[i]); } return 0; }
Solution C++
#include<iostream> #include<algorithm> #include<string> using namespace std; const int N = 105; int a[N],b[N],c[N]; void input(int a[]){ fill(a,a+N,0); string s; cin>>s; a[0]=s.size(); for (int i=1; i<=a[0]; i++) a[i]=s[a[0]-i]-48; } void add(int a[],int b[],int c[]){ fill(c,c+N,0); c[0]=a[0]>b[0]?a[0]:b[0]; for (int i=1; i<=c[0]; i++) { c[i]+=a[i]+b[i]; c[i+1]+=c[i]/10; c[i]%=10; } if (c[c[0]+1]) c[0]++; } void output(int a[]){ for (int i=a[0]; i>=1; i--) cout<<a[i]; cout<<endl; } int main(){ input(a); input(b); add(a,b,c); output(c); return 0; }