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. }  
发布了52 篇原创文章 · 获赞 86 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/dianxin113/article/details/77887422