HDU 1002 A + B Problem II(大数相加)
HDU 1002
A + B Problem II
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
#include<stdio.h>
#include<string.h>
int main(){
int i,j,k,n,flag=0,len1,len2,sum,len=0;
while(scanf("%d",&n)!=EOF){
for(k=1;k<=n;k++){
char s1[1001],s2[1001];
int ans[1001]={0};
scanf("%s %s",s1,s2);
len1=strlen(s1);
len2=strlen(s2);
if(len1>=len2)
{ len=len1;
j=len2-1;
for(i=len1-1;i>=0;i--){
if(j>=0){
sum=(int)s1[i]+(int)s2[j--]-96+flag;
if(sum>=10){
ans[i]=sum%10;
flag=1;
}
else{
ans[i]=sum;
flag=0;
}
}
else{
sum=(int)s1[i]-48+flag;
if(sum>=10){
ans[i]=sum%10;
flag=1;
}
else{
ans[i]=sum;
flag=0;
}
}
}
}
else if(len1<len2)
{ len=len2;
j=len1-1;
for(i=len2-1;i>=0;i--){
if(j>=0){
sum=(int)s1[j--]+(int)s2[i]-96+flag;
if(sum>=10){
ans[i]=sum%10;
flag=1;
}
else{
ans[i]=sum;
flag=0;
}
}
else{
sum=(int)s2[i]-48+flag;
if(sum>=10){
ans[i]=sum%10;
flag=1;
}
else{
ans[i]=sum;
flag=0;
}
}
}
}
if(k>1) printf("\n");
printf("Case %d:\n",k);
if(flag==0){
printf("%s + %s = ",s1,s2);
for(i=0;i<len-1;i++) printf("%d",ans[i]);
printf("%d\n",ans[len-1]);
}
if(flag==1){
printf("%s + %s = 1",s1,s2);
for(i=0;i<len-1;i++) printf("%d",ans[i]);
printf("%d\n",ans[len-1]);
}
}
}
}
Note:
算法和思路是很简单的,主要是实现的方法,我这个基础知识太烂,搞了半天
就是从后往前运算,然后进位就行呗
我最得意的一点是 flag的用法
最前一位的时候flag是1的话就在前面+1,是0就不用加
浙公网安备 33010602011771号