HDU1002 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): 162637    Accepted Submission(s): 30973


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

解题思路:本题有2种解法,一是用C++,数组模拟位数存储,后面栈处理后输出即可;二是直接用JAVA,有大数处理方法,直接处理输出即可。题目的小陷阱在格式,输出的东东里面,每两个元素之间都有空格,测试数据组间要输出空行,最后一组数据输出后面不能有空行。


#include<cstdio> #include<cstring> #include<stack> using namespace std; int main() {     int n;     scanf("%d",&n);     for(int x=1;x<=n;x++)     {         stack<int> s;        char a[1000],b[1000];        int sum=0;        scanf("%s%s",a,b);         int stra=strlen(a);        int strb=strlen(b);        int i,j;        for(i=stra-1,j=strb-1;i>=0&&j>=0;i--,j--)        {             sum+=a[i]-'0'+b[j]-'0';             s.push(sum%10);    //由于是由后面低位开始处理的,输出时要由高位到低位输出,故用栈处理             sum/=10;    //记录上一位进位情况        }        if(i>=0)   //第一个数位数较多        {             for(;i>=0;i--)             {                 sum+=a[i]-'0';                 s.push(sum%10);                 sum/=10;             }        }        else   //第二个数位数较多        {             for(;j>=0;j--)             {                 sum+=b[j]-'0';                 s.push(sum%10);                 sum/=10;             }        }        if(x!=1)         printf("\n");        printf("Case %d:\n",x);        printf("%s + %s = ",a,b);        while(!s.empty())        {            printf("%d",s.top());            s.pop();        }        printf("\n");     }     return 0; }


import java.math.*; import java.util.*; class Main{   public static void main(String args[])  {     Scanner as=new Scanner(System.in);     BigInteger n,m;     int x,i;     x=as.nextInt();     for(i=1;i<=x;i++)     {         if(i>1) System.out.println();         n=as.nextBigInteger();         m=as.nextBigInteger();         System.out.println("Case "+i+":");         System.out.println(n+" + "+m+" = "+n.add(m));    //不解释,直接用方法     }   } } 


你可能感兴趣的:(HDU1002 A + B Problem II)