hdu 1002 A + B Problem II (大數加法)

 
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
 
 
思路:這題除了格式有點坑之外還行,我這裏把大數加法用個函數表示,顯得更清晰明瞭......
 
 
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<cmath>
 5 #include<algorithm>
 6 #include<map>
 7 #include<vector>
 8 #include<set>
 9 #include<queue>
10 using namespace std; 11 #define ll long long 
12 
13 string Sum(string a,string b)//大數加法 
14 { 15     //補前導零 
16     while(a.size()<b.size()) 17         a.insert(0,"0"); 18     while(b.size()<a.size()) 19         b.insert(0,"0"); 20     
21     string ans="";//記錄結果 
22     
23     int jinwei=0,sum,yu;//運算所需 
24     
25     for(int i=a.size()-1;i>=0;i--)//從末尾算起 
26  { 27         sum=(a[i]-'0')+(b[i]-'0')+jinwei; 28         jinwei=sum/10; 29         yu=sum%10; 30         ans+=(yu+'0');//加上這一位的餘數 
31  } 32     if(jinwei)//可能多一位 
33         ans+=(jinwei+'0'); 34     
35     reverse(ans.begin(),ans.end());//因爲是從末尾算起,須要逆置字符串 
36     
37     return ans; 38 } 39 
40 int main() 41 { 42     ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); 43     
44     int T; 45     
46     cin>>T; 47     
48     string a,b,s; 49     
50     for(int k=1;k<=T;k++) 51  { 52         cin>>a>>b; 53         s=Sum(a,b); 54         
55         cout<<"Case "<<k<<":"<<endl; 56         cout<<a<<" + "<<b<<" = "<<s<<endl; 57         
58         if(k!=T) 59             cout<<endl; 60  } 61     return 0; 62 }
相關文章
相關標籤/搜索