A+B超过long long 大数相加问题


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
 
像大数这一类题目一般都是用 string 来做, 这个题首要把两个字符串用 reverse 倒序过来运算(由于数字运算是从个位,十位 .....)。最后再倒序回来。
注意:1.这里的运算并不是字符间直接运算,而是转化成 int 型在加减运算。
           2.转化成 int 型的两个数运算后可能出现超过 10 ,一定要记得进位

[cpp]  view plain  copy
  1. #include<iostream>  
  2. #include<string>  
  3. using namespace std;  
  4. char add(char temps,char tempstr,int &tempaddc)  
  5. {  
  6.     int temp;   
  7.     temp = (temps - '0') + (tempstr - '0') + tempaddc;  //实现进位。  
  8.     tempaddc = temp / 10;  // 算出进位数  
  9.     return temp % 10 + '0';  
  10. }  
  11. int main()  
  12. {  
  13.     string str,s;  
  14.     int tempaddc;  
  15.     char c;  
  16.     int n,lenstr,lens;  
  17.     while(cin>>n)  
  18.     {  
  19.         while(n--)  
  20.         {  
  21.             cin>>str>>s;  
  22.             tempaddc = 0;  
  23.             c = '0';  
  24.             if(s.length() > str.length())swap(s,str);  
  25.             lenstr = str.length();  
  26.             lens = s.length();  
  27.             lens--;  
  28.             lenstr--;  
  29.             while (lenstr >= 0)  
  30.             {  
  31.                 if(lens < 0) str[lenstr] = add(c,str[lenstr],tempaddc);    //字符串长度较长部分的计算  
  32.                 else  
  33.                 {  
  34.                     str[lenstr] = add(s[lens],str[lenstr],tempaddc);  
  35.                     lens--;  
  36.                 }  
  37.                 lenstr--;  
  38.             }  
  39.             cout<<str<<endl;  
  40.         }  
  41.     }  
  42.     return 0;  
  43. }  
全部评论

相关推荐

迟缓的斜杠青年巴比Q了:简历被投过的公司卖出去了,我前两天遇到过更离谱的,打电话来问我有没有意向报班学Java学习,服了,还拿我学校一个学长在他们那报班学了之后干了华为OD当招牌
点赞 评论 收藏
分享
05-12 11:09
已编辑
门头沟学院 后端
已注销:没必要放这么多专业技能的描述。这些应该是默认已会的,写这么多行感觉在凑内容。项目这块感觉再包装包装吧,换个名字,虽然大家的项目基本都是网上套壳的,但是你这也太明显了。放一个业务项目,再放一个技术项目。技术项目,例如中间件的一些扩展和尝试。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务