乐逍遥xwl

导航

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 }

 

 

 

posted on 2019-06-17 18:21  乐逍遥xwl  阅读(236)  评论(0编辑  收藏  举报