A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 367705 Accepted Submission(s): 71628
Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
Input
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.
Output
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. Output a blank line between two test cases.
Sample Input
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
一道A+B的題,但是是一道大數題,需用字符串,記得第一次做這道題的時候是在一場訓練賽上,當時的水平停留在水題階段,沒有見識過大數題,字符串也學得不怎麼樣,當時總覺得自己做得沒錯,但是一直WR,現在再做這道題,感覺蠻輕鬆,附上代碼
#include<stdio.h>
#include<string.h>
int shu (char a)
{
return (a-'0');//將字符串轉換爲數字
}
int main()
{
char a[1000];
char b[1000];
int num[10000];
int s,n,a1,b1,k,i,count=1;
scanf("%d",&n);
while(n--)
{
if(count!=1)
{
printf("\n");
}
scanf("%s",&a);
scanf("%s",&b);
a1=strlen(a);//a字符串的長度
b1=strlen(b);//b字符串的長度
k=(a1>b1)?a1:b1;
for(i=0;i<=k;i++)
{
num[i]=0;//初始化
}
s=k;
for(k;a1>0&&b1>0;k--)//在a,b不等長的情況下,得出每個a+b直到沒有a或者b爲止
{
num[k]=num[k]+shu(a[--a1])+shu(b[--b1]);
if(num[k]/10)
{
num[k-1]++;
num[k]%=10;
}
}
while(a1>0)//若a>b則把a遺漏的加上
{
num[k--]+=shu(a[--a1]);
if(num[k+1]/10)//注意前面已經k--,求上一個數的時候k+1
{
num[k]++;
num[k+1]=num[k+1]%10;
}
}
while(b1>0)//若b>a則把b遺漏的加上
{
num[k--]+=shu(b[--b1]);
if(num[k+1]/10)
{
num[k]++;
num[k+1]=num[k+1]%10;
}
}
printf("Case %d:\n",count++);
printf("%s + %s = ",a,b);
for(i=0;i<=s;i++)
{
if(i==0&&num[i]==0)//注意若第一個爲0不輸出
{
i++;
}
printf("%d",num[i]);
}
printf("\n");
}
return 0;
}