A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 388690 Accepted Submission(s): 75226
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
这题用大数加法做才行,或者用Java做。
发现自己好粗心啊。
1 #include <iostream> 2 #include <bits/stdc++.h> 3 #include <cstring> 4 #include <cstdio> 5 #include <string> 6 #define N 1010 7 using namespace std; 8 int n; 9 int k[N]; 10 void bigdate(string a,int alen,string b,int blen){ 11 reverse(a.begin(),a.end()); 12 reverse(b.begin(),b.end()); 13 for(int i=0;i<alen;i++){ 14 int an=a[i]-'0',bn=b[i]-'0'; 15 if(an+bn+k[i]>9){ 16 k[i]=(an+bn+k[i]-10); 17 k[i+1]++; 18 }else{ 19 k[i]+=(an+bn); 20 } 21 } 22 if(alen<blen) 23 for(int i=alen;i<blen;i++){ 24 k[i]+=(b[i]-'0'); 25 } 26 } 27 int main(){ 28 cin>>n; 29 for(int p=1;p<=n;p++){ 30 string a,b; 31 cin>>a>>b; 32 memset(k,0,sizeof(k)); 33 int alen=a.length(); 34 int blen=b.length(); 35 if(alen<blen) 36 bigdate(a,alen,b,blen); 37 else 38 bigdate(b,blen,a,alen); 39 cout<<"Case "<<p<<":"<<endl; 40 cout<<a<<" + "<<b<<" = "; 41 if(k[max(alen,blen)]!=0) 42 cout<<k[max(alen,blen)]; 43 for(int i=max(alen,blen)-1;i>=0;i--) 44 cout<<k[i]; 45 if(p!=n) 46 cout<<endl<<endl; 47 else 48 cout<<endl; 49 } 50 return 0; 51 }
Java代码
1 import java.util.*; 2 import java.math.*; 3 public class Main{ 4 public static void main(String[] args){ 5 Scanner scanner =new Scanner(System.in); 6 int n=scanner.nextInt(); 7 for(int i=1;i<=n;i++){ 8 if(i!=1) 9 System.out.println(); 10 BigInteger a,b; 11 a=scanner.nextBigInteger(); 12 b=scanner.nextBigInteger(); 13 System.out.println("Case "+i+":"); 14 System.out.println(a+" + "+b+" = "+a.add(b)); 15 } 16 } 17 }