问题如下:应用中经常遇到大数运算问题。请设计无符号大数类,能支持无符号大数像普通无符号数一样进行+、-、比较等运算和输出。假定本题大数在200位以内,提示:采用字符串方式输入大数,不要用getline输入,无符号大数内部存放时建议按低位到高位次序存放各位数字,便于无符号大数类扩展到支持乘、除运算。
输入格式:
两个无符号大数 (第一个大数不小于第二个大数),中间用空格、'\t'或'\n'分隔。
输出格式:
输出它们的和、差
输入样例:
1234567890987654321333888999666
147655765659657669789687967867
输出样例:
1382223656647311991123576967533
1086912125327996651544201031799
代码如下:
#include <iostream>
#include <string>
#include <algorithm>
class BigInteger {
private:
std::string number;
public:
BigInteger(const std::string& num) : number(num) {
std::reverse(number.begin(), number.end()); // 按低位到高位顺序存放
}
BigInteger add(const BigInteger& other) const {
std::string result;
int carry = 0;
size_t i = 0;
for (; i < std::min(this->number.size(), other.number.size()); ++i) {
int digit1 = this->number[i] - '0';
int digit2 = other.number[i] - '0';
int sum = digit1 + digit2 + carry;
carry = sum / 10;
result.push_back(sum % 10 + '0');
}
for (; i < this->number.size(); ++i) {
int sum = (this->number[i] - '0') + carry;
carry = sum / 10;
result.push_back(sum % 10 + '0');
}
for (; i < other.number.size(); ++i) {
int sum = (other.number[i] - '0') + carry;
carry = sum / 10;
result.push_back(sum % 10 + '0');
}
if (carry > 0) {
result.push_back(carry + '0');
}
std::reverse(result.begin(), result.end()); // 恢复正常的顺序
return BigInteger(result);
}
BigInteger subtract(const BigInteger& other) const {
std::string result;
int borrow = 0;
for (size_t i = 0; i < this->number.size(); ++i) {
int digit1 = i < this->number.size() ? this->number[i] - '0' : 0;
int digit2 = i < other.number.size() ? other.number[i] - '0' : 0;
int diff = digit1 - digit2 - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result.push_back(diff + '0');
}
// 去除结果字符串的前导零(如果有)
size_t nonZeroPos = result.find_first_not_of('0');
if (nonZeroPos != std::string::npos) {
result = result.substr(nonZeroPos);
} else {
result = "0";
}
std::reverse(result.begin(), result.end()); // 恢复正常的顺序
return BigInteger(result);
}
// 提供一个转换函数,方便打印
std::string toString() const {
std::string reversedCopy = number;
std::reverse(reversedCopy.begin(), reversedCopy.end());
return reversedCopy;
}
};
int main() {
std::string num1, num2;
// 使用std::cin直接读取一行,避免getline等可能引起的输入问题
std::cin >> num1;
std::cin >> num2;
BigInteger bigInt1(num1), bigInt2(num2);
std::cout << bigInt1.add(bigInt2).toString() << std::endl; // 输出和
std::cout << bigInt1.subtract(bigInt2).toString() ; // 输出差
return 0;
}