Problem A+B(Big Integer)
Time Limit:1000MS Memory Limit:65536KB
Description
Give two positive integer A and B,calucate A+B.
Notice that A,B is no more than 500 digits.
Input
The test case contain several lines.Each line contains two positive integer A and B.
Output
For each input line,output a line contain A+B
Sample Input
2 3
1231231231823192 123123123123123
1000000000000000 1
Sample Output
5
1354354354946315
1000000000000001
此题是我们熟悉的大数相加,顾名思义大数肯定是超出int等基本类型范围的,因为必须采用字符串来模拟手工计算,是不是一夜回到小学的感觉,那就没啥了,直接上代码吧。有个注意点是如果两个数相加最高位产生进位,这个情况要注意下。比如:9+1=10,999+1=1000等。废话不多说了直接上代码:
#include <iostream> #include <string> #include <cstdlib> using namespace std; int main() { string a,b,sum; int diff,length; int carry = 0; while(cin >> a >> b) { if(a.length() < b.length()) { b.insert(0,"0"); diff = b.length() - a.length(); a.insert(0,diff,'0'); sum = b; } else if (a.length() > b.length()) { a.insert(0,"0"); diff = a.length() - b.length(); b.insert(0,diff,'0'); sum = a; } else//为了防止最高位进位,在前面多加一位 { a.insert(0,"0"); b.insert(0,"0"); sum = b; } length = sum.length(); for(int i = length-1; i >= 0; --i) { int temp_a = a[i] - '0'; int temp_b = b[i] - '0'; int s = temp_a + temp_b; if(s + carry > 9) { sum[i] = s + carry - 10 + '0'; carry = 1; } else { sum[i] = s + carry + '0'; carry = 0; } } if(sum[0] == '0')//把最高位的0去掉 { sum.erase(0,1); } cout << sum << endl; sum.clear(); } return 0; }