编程实现求a+b的和
Problem Description
Now let’s calculate the answer of a + b ~
Input
The input will consist of a set of pairs of integers for a and b(-10^1000 <= a, b <= 10^1000). The input is ended by EOF.
Output
For each test case you should output the answer of a + b.
Sample Input
1 1
1 -1
Sample Output
2
0
大家可以讨论下,要求执行时间限制为1s,内存尽可能小,
[解决办法]
MS就是一个大数相加吧?
- C/C++ code
#include <string>#include <iostream>#include <algorithm>using namespace std;string PLUS(string number1,string number2) { int i; int length1 = number1.size(); int length2 = number2.size(); string result=""; reverse(number1.begin(), number1.end()); reverse(number2.begin(), number2.end()); for(i = 0; i < length1 && i < length2; i++) { char c = (char)(number1[i] + number2[i] - 48); result = result + c; } while(i < length1) { result = result + number1[i]; ++i; } while(i < length2) { result = result + number2[i]; ++i; } int carry = 0; for(i = 0; i < (int)result.size(); ++i) { int value = result[i] - 48 + carry; result[i] = (char)(value % 10 + 48); carry = value / 10; } if(carry !=0 ) { result = result + (char)(carry + 48); } for(i = result.size() - 1; i >= 0; i--) { if(result[i] != '0') break; } result = result.substr(0, i + 1); reverse(result.begin(), result.end()); if(result.length() == 0) result = "0"; return result;}void main(){ string add1,add2; while(cin>>add1>>add2!=0||add1.size()<1001||add2.size()<1001) { cout<<PLUS(add1,add2); } }