a+b(华中科技大学复试上机题)
题目描述
实现一个加法器,使其能够输出a+b的值。
输入描述:
输入包括两个数a和b,其中a和b的位数不超过1000位。
输出描述:
可能有多组测试数据,对于每组数据,
输出a+b的值。
示例1
输入
2 6
10000000000000000000 10000000000000000000000000000000
输出
8
10000000000010000000000000000000
题目思路
这题就是道大整数计算,是到模板题,这道题只用到了加法,在这里有加、减、乘、除、取模、输入、输出等一系列的运算,但是仅限制正整数的运算。
代码如下
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
using namespace std;
const int MAXN = 10000;
struct BigInteget
{
int digit[MAXN];
int length;
BigInteget();
BigInteget operator =(string str);
BigInteget operator +(const BigInteget & b);
friend istream& operator>>(istream& in, BigInteget& x);
friend ostream& operator<<(ostream& out, const BigInteget& x);
};
istream& operator>>(istream& in, BigInteget& x)
{
string str;
in >> str;
x = str;
return in;
}
ostream& operator<<(ostream& out, const BigInteget& x)
{
for(int i = x.length-1; i >= 0; i--)
out << x.digit[i];
return out;
}
BigInteget::BigInteget()
{
memset(digit, 0, sizeof(digit));
length = 0;
}
BigInteget BigInteget::operator=(string str)
{
memset(digit, 0, sizeof(digit));
length = str.size();
for(int i = 0; i < length; i++)
digit[i] = str[length-i-1] - '0';
return *this;
}
BigInteget BigInteget::operator+(const BigInteget& b)
{
BigInteget answer;
int carry = 0;
for(int i = 0; i < length || i < b.length; i++)
{
int current = carry + digit[i] + b.digit[i];
carry = current /10;
answer.digit[answer.length++] = current%10;
}
if(carry)
{
answer.digit[answer.length++] = carry;
}
return answer;
}
int main()
{
BigInteget a, b;
while(cin >> a >> b)
cout << a + b << endl;
return 0;
}