#include

HDU1002:A + B Problem II(两个大正整数和)

HDU1002:A + B Problem II(两个大正整数和)

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 376617    Accepted Submission(s): 73403


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 <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std ;

#define maxn 2000
char num1[maxn] , num2[maxn] ;
int result[maxn] , n1[maxn] , n2[maxn] ;


int main() {
    int t ;
    scanf("%d" , &t) ;
    for(int times =1 ; times <= t ; times ++ ) {
        scanf("%s %s" , num1 , num2) ;
        printf("Case %d:\n" , times ) ;
        printf("%s + %s = " , num1 , num2 ) ;
        int len1 = strlen(num1) , len2 = strlen(num2) ;
        int k, i , j ;
        int len = max(len1 , len2) ;
        memset(n1 , 0 , sizeof(n1)) ; 
        memset(n2 , 0 , sizeof(n2)) ; 
        
        for( i=len1-1 , k=0 ; i>=0 ; i--) {
            n1[k++] = num1[i] -'0' ;
        }
        for(i=len2-1 , k=0 ; i>=0 ; i--) {
            n2[k++] = num2[i] -'0';
        }
        // 模拟加法 
        int cnt = 0 ; 
        for(int i=0 ; i<len ; i++){
            result[i] = (n1[i] + n2[i] + cnt ) % 10 ; 
            cnt = (n1[i] + n2[i] + cnt ) / 10 ;
        }
        if(cnt>0)
            result[len++] = cnt ; 
        int flag = 0 ; 
        for(int i=len-1 ; i>=0 ; i--){
            //正数加正数  没必要处理前导 0 (因为不存在......) 
                    printf("%d" , result[i]) ; 
            
        }
        printf("\n") ; 
        if(times != t)
            printf("\n") ; 
             
    }
    return 0 ;
}

 

posted @ 2017-10-12 22:09  0一叶0知秋0  阅读(169)  评论(0编辑  收藏  举报