大数加法基本思路都有,但是有思路和写代码完全两码事啊,好不容易捋清楚了。记下来,嗯嗯~~
题目描述:(英文描述,英文不好伤不起。)
A+B Problem II
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
A,B must be positive.
-
输入
- The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000. 输出
- For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. 样例输入
-
2 1 2 112233445566778899 998877665544332211
样例输出
-
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
#include <stdio.h>
#include <memory.h>
#include <string.h>
int main()
{
int T,i,m,n,max,min,t,count = 1,j;
int sum[1000],c[1000];
char str1[1000],str2[1000],str3[1000],str4[1000];
scanf("%d",&T);
while(T --)
{
memset(sum,0,sizeof(sum));
scanf("%s%s",str1,str2);
m = strlen(str1);
n = strlen(str2);
if(str1[0] == '0' && str2[0] == '0')//0+0的情况
{
printf("0 + 0 = 0\n");
continue;
}
printf("Case %d:\n",count);
count ++;
printf("%s + %s = ",str1,str2);
for(i=0; i<m; i++)//字符串倒置
str3[i] = str1[m-1-i];
str3[i] = 0;
for(i=0; i<n; i++)
str4[i] = str2[n-1-i];
str4[i] = 0;
max = m > n ? m : n;
min = m < n ? m : n;
for(i=m; i<max; i++)//长度不一时补位
{
str3[i] = '0';
}
str3[i] = 0;
for(i=n; i<max; i++)
{
str4[i] = '0';
}
str4[i] = 0;
for(i=0; i<max; i++)//按位加,存到数组里
{
sum[i] = str3[i]-'0'+ str4[i]-'0';
}
t = 0;
j = max;
for(i=0; i<=max; i++)//进位
{
c[i] = (sum[i] + t) % 10;
t = (sum[i] + t) / 10;
}
while(c[i-1] == 0)//处理数前的0
{
i --;
j --;
}
for(i=j; i>=0; i--)
printf("%d",c[i]);
printf("\n");
}
return 0;
}