HDU-1002 A + B Problem II
Posted bethebestone
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU-1002 A + B Problem II相关的知识,希望对你有一定的参考价值。
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 515227 Accepted Submission(s): 98635
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的话,就可以直接用大数进行计算
但是练习一下C++的大数加法还是挺好的
这道题C++不能直接进行大数的加法,所以我采用string数组来进行辅助计算,会比较简单一些
利用string的相关函数进行操作会比较便捷
还有就是一些加法上的小细节了,注意进位之类的,从后往前加,然后还要注意有没有加完
代码如下:
1 #include<bits/stdc++.h> 2 #define mem(a) memset(a,0,sizeof(a)) 3 #define forn(i,n) for(int i=0;i<n;++i) 4 #define for1(i,n) for(int i=1;i<=n;++i) 5 #define IO std::ios::sync_with_stdio(false); std::cin.tie(0) 6 using namespace std; 7 typedef long long ll; 8 const int maxn=1e3+5; 9 const int mod=10007; 10 const int inf=0x3f3f3f3f; 11 12 ll n,m,t,k; 13 string num1,num2; 14 15 string add(string stra,string strb) 16 { 17 string res; 18 string str1=stra; 19 string str2=strb; 20 reverse(str1.begin(),str1.end()); 21 reverse(str2.begin(),str2.end()); 22 int i=0; 23 int x=0; 24 while(i<str1.size()&&i<str2.size()) 25 { 26 int a=str1[i]-‘0‘; 27 int b=str2[i]-‘0‘; 28 int c=a+b+x; 29 x=c/10; 30 c=c%10; 31 char s=‘0‘+c; 32 res=s+res; 33 i++; 34 } 35 if(i<str1.size()) 36 { 37 while(i<str1.size()) 38 { 39 str1[i]=str1[i]+x; 40 int w=str1[i]-‘0‘; 41 x=w/10; 42 w=w%10; 43 str1[i]=‘0‘+w; 44 res=str1[i]+res; 45 i++; 46 } 47 } 48 if(i<str2.size()) 49 { 50 while(i<str2.size()) 51 { 52 str2[i]=str2[i]+x; 53 int w=str2[i]-‘0‘; 54 x=w/10; 55 w=w%10; 56 str2[i]=‘0‘+w; 57 res=str2[i]+res; 58 i++; 59 } 60 } 61 if(x==1) 62 { 63 char cc=‘1‘; 64 res=cc+res; 65 } 66 return res; 67 } 68 69 int main() 70 { 71 IO; 72 cin>>m; 73 int k=1; 74 while(k<=m) 75 { 76 if(k!=1) 77 cout<<endl; 78 cin>>num1>>num2; 79 string ans=add(num1,num2); 80 cout<<"Case "<<k<<":"<<endl; 81 cout<<num1<<" + "<<num2<<" = "<<ans<<endl; 82 k++; 83 } 84 return 0; 85 }
以上是关于HDU-1002 A + B Problem II的主要内容,如果未能解决你的问题,请参考以下文章