hduoj #1002 A + B Problem II

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002
题目描述如下:


A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/32768 K (Java/Others)

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  

题目大意: 大数相加
题目思路: 从最低位开始一位一位的加。注意进位,注意清除前缀的0
C++ 代码如下:

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    int n;
    char a[1001],b[1001];
    short c[1001];
    cin >> n;
    for (int i=0; i<n; i++)
    {
        int alen,blen,clen,maxlen;
        cin >> a >> b;
        alen = strlen(a);
        blen = strlen(b);
        clen = 0;
        maxlen = alen/blen ? alen : blen;
        int ai,bi,s=0;
        for (int j=0; j<maxlen; j++)
        {
            ai = alen-j-1;
            bi = blen-j-1;
            if (ai>=0 && bi>=0)
                s = a[ai]+b[bi]-2*'0'+s/10;
            else if (ai>=0)
                s = a[ai]-'0'+s/10;
            else if (bi>=0)
                s = b[bi]-'0'+s/10;
            c[clen++] = s%10;
        }
        if (s/10)
            c[clen++] = s/10;
        for (int k=clen-1; k>=0; k--)
            if (c[k])
                break;
            else
                clen--;
        cout << "Case " << i+1 << ":" << endl;
        cout << a <<" + " << b << " = ";
        for (int k=clen-1; k>=0; k--)
            cout << c[k];
        cout << endl;
        if (n-i-1)
            cout << endl;
    }
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,889评论 0 23
  • 谦谦君子, 温文尔雅。 我想你,陪我身旁, 你悄悄,关上心房。 我在故乡,思念情郎。 你在他乡,仰望月亮。 我强求...
    喜乐安阅读 177评论 0 0
  • 新的一年新的开始,我在慢慢的喜欢自己。我想这是一件好事情。 回想过去一年,有委屈有心酸,有幸福也时常开心。好坏参半...
    九姝子阅读 246评论 0 1
  • 早上没起得来,九点起床后随便玩玩就吃午饭,下午玩会后就睡到四点多,做了会汇编作业就去吃饭上课,汇编课收获不少。回寝...
    沐风97阅读 199评论 0 0