EOJ1001. Problem A+B (Big Integer)

 单点时限: 2.0 sec

内存限制: 256 MB

Give two positive integer A and B, calucate A+B.

Notice that A,B is no more than 500 digits.

输入格式

The test case contain several lines. Each line contains two positive integer A and B.

输出格式

For each input line, output a line contain A+B.

样例

input

2 3
1231231231823192 123123123123123
1000000000000000 1

output

5
1354354354946315
1000000000000001

主要思路是:

第一步:将 A 和 B 两个数从个位开始,对逐位的char型变量进行相加,加和完成之后得到一个【部分位可能超过10的字符串】。

第二步:对该字符串重新整理,从个位开始,遇到【>=10的数字】就对高位进行进位。

第三步:检查最高位进位,如果仍需要进位,对字符串开头要添一个“1”

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define OFFSET 	'0'

int main() {
	string a, b;
	while (cin >> a >> b) {
		// begin in lowest positional set
		string::reverse_iterator ita = a.rbegin();
		string::reverse_iterator itb = b.rbegin();
		for (; ita != a.rend() && itb != b.rend(); ita++, itb++) {
			if (a.length() >= b.length()) {
				*ita += *itb - OFFSET;
			} else {
				*itb += *ita - OFFSET;
			}
		}	//get raw data in A or B
		
		string itemp = a.length() >= b.length() ? a : b;
		string::reverse_iterator it;
		for (it = itemp.rbegin(); it != itemp.rend(); it++) {
			if (*it > '9') {
				*it -= 10;
				if (it + 1 != itemp.rend()) {	// head-postion need up.
					*(it + 1) += 1;
				} else {
					itemp.insert(itemp.begin(), '1');
					break;	// BREAK is a must
				}
			}
		}
		cout << itemp << endl;
	}
	return 0;
}

最后效率还不错诶 =v=

猜你喜欢

转载自blog.csdn.net/qingxiu3733/article/details/131492493