Problems A: a + b (large integers)

Implement an adder, it is possible to output the value of a + b.

Entry

Input comprises a number of two and b, where a and b is not more than 1000 bits.

Export

It may be multiple sets of test data for each set of data,
the output of the value of a + b.

Sample input Copy

6 8
2000000000 30000000000000000000

Sample output Copy

14
30000000002000000000
#include <iostream>
#include <string.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct bign {
	int d[1005];
	int len;
	bign() {
		memset(d, 0, sizeof(d));
		len = 0;
	}
};
bign change(string s) {
	bign a;
	int len = s.length();
	for(int i = len - 1; i >= 0; i--) {
		a.d[a.len++] = s[i] - '0';
	}
	return a;
}
void output(bign a) {
	for(int i = a.len - 1; i >= 0; i--) {
		printf("%d", a.d[i]);
	}
}

bign add(bign a, bign b) {
	bign c;
	int carry = 0;//进位
	for(int i = 0; i < a.len || i < b.len; i++) {
		int temp = a.d[i] + b.d[i] + carry;
		c.d[c.len++] = temp % 10;//个位赋给c
		carry = temp / 10;
	}
	if(carry != 0) { //进位不为零赋给高位
		c.d[c.len++] = carry;
	}
	return c;
}
int main(int argc, char** argv) {
	string s1, s2;
	while(cin >> s1 >> s2) {
		bign a = change(s1);
		bign b = change(s2);
		bign c = add(a, b);
		output(c);
		cout << endl;
	}
	return 0;
}

 

Published 85 original articles · won praise 1 · views 5189

Guess you like

Origin blog.csdn.net/lx18303916/article/details/104511096