A + B Problem II(1002)

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 .   注意!!!一定要将两个新的整型数组初始化为0(这长度不一的两个数倒叙相加时不会出错),另外最好用一个新的数组来接受相加结果。。  
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;

int main()
{
    int n , ans = 0;
    cin >> n ;
    while(n --)
    {
        ans++ ;
        char a[10000] = {0},  b[10000] ={0} ;
        int c[10000] ={0}, d[10000] = {0} , e[10000] ={0};
        scanf("%s%s" , &a , &b);
        int len1 = strlen(a) ;
        int len2 = strlen(b) ;
        int len = max(len1 , len2);
        int j = 0 ;
        for(int i = len1 - 1 ; i >= 0 ; i--)
        {
            c[j++] = a[i] - 48 ;
        }
        j = 0 ;
        for(int i = len2 - 1 ; i >= 0 ; i--)
        {
            d[j++] = b[i] - 48 ;
        }
        int k = 0 ;
        for(int i = 0 ; i < len ; i++)
        {
            e[i] = (c[i] + d[i] + k) % 10 ;
            k =  (c[i] + d[i] + k) / 10 ;
        }
        cout << "Case " << ans << ':' << endl ;
        printf("%s + %s = " , a , b);
        if(!k)
        {
            for(int i = len - 1 ; i >= 0 ; i--)
                cout << e[i] ;
            cout << endl ;
        }
        else
        {
            e[len] = k ;
            for(int i = len ; i >= 0 ; i--)
                cout << e[i] ;
            cout << endl ;
        }
        if(n != 0)
            printf("\n");


    }
    return 0;
}

 

 
上一篇:1002.查找常用字符


下一篇:WQ7033开发指南(基础篇)之1.2 烧录固件详解