HDU-1002 A + B Problem II(大整数加法)

版权声明:Copyright : 李三金,原创文章转载标明出处即可。 https://blog.csdn.net/santa9527/article/details/53741643

HDU-1002 A + B Problem II

A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 336849 Accepted Submission(s): 65348

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

Author
Ignatius.L

最简单的大数A+B,今天复习一下,顺手写一个博客。
题目有坑点,不过以前遇到过,所以也没啥了。

扫描二维码关注公众号,回复: 3532753 查看本文章

大数A+B就是一个代码模拟自己手算A+B的过程,具体看代码和注释。

#include<bits/stdc++.h>
using namespace std;
char s1[1024],s2[1024],res[1024],s11[1024],s22[1024];
void ac(char *s)//将字符串倒过来,个人觉得方便理解,也可以不倒,自己想为什么
{
    for(int i=0; i<strlen(s)-1-i; i++)//注意终止条件
        swap(s[i],s[strlen(s)-1-i]);
}
int main()
{
    int t;
    int i,j=1,k;
    int acc,tmp;
    scanf("%d",&t);
    while(t--)
    {
        if(j!=1) printf("\n");//坑点,输出格式
        scanf("%s %s",s1,s2);//字符串输入大整数
        int len1=strlen(s1),len2=strlen(s2);
        strcpy(s11,s1);//题目真恶心= =,
        strcpy(s22,s2);

        ac(s1);
        ac(s2);

        acc=0;//保留进位
        for(i=0; i<len1&&i<len2; i++)
        {
            tmp=s1[i]-'0'+s2[i]-'0'+acc;//字符转换成数字后相加,别忘了进位
            res[i]=tmp%10+'0';
            acc=tmp/10;
        }
        if(i<len1)//考虑两个数字位数不同
            for(;i<len1;i++)
        {
            tmp=s1[i]-'0'+acc;
            res[i]=tmp%10+'0';
            acc=tmp/10;
        }
        if(i<len2)//同上
            for(;i<len2;i++)
        {
            tmp=s2[i]-'0'+acc;
            res[i]=tmp%10+'0';
            acc=tmp/10;
        }
        if(acc) res[i++]='1';//最后,如果还能进一位,记得进上去
        res[i]='\0';//很重要!!!,因为是字符串,所以要记得\0,不然会出错
        ac(res);//最后再将结果倒过来,因为开始是倒过来的
        printf("Case %d:\n%s + %s = ",j++,s11,s22);
        printf("%s\n",res);
    }
}

以上。

猜你喜欢

转载自blog.csdn.net/santa9527/article/details/53741643
今日推荐