P1601 A+B Problem(高精)
算法分类:高精度运算
链接:洛谷OJ
题目描述
高精度加法,相当于 a+b problem,不用考虑负数。
输入格式
分两行输入。 a , b ≤ 1 0 500 a,b \leq 10^{500} a,b≤10500。
输出格式
输出只有一行,代表 a + b a+b a+b 的值。
输入输出样例 #1
输入 #1
1
1
输出 #1
2
输入输出样例 #2
输入 #2
1001
9099
输出 #2
10100
说明/提示
20 % 20\% 20% 的测试数据, 0 ≤ a , b ≤ 1 0 9 0\le a,b \le10^9 0≤a,b≤109;
40 % 40\% 40% 的测试数据, 0 ≤ a , b ≤ 1 0 18 0\le a,b \le10^{18} 0≤a,b≤1018。
题解
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std; // 使用标准命名空间简化代码
class BigInt {
private:
vector<int> digits; // 存储大数的每一位数字,低位在前(个位在digits[0])
// 清除前导零的辅助方法
void trimLeadingZeros() {
// 当数字有多位且最高位为0时(比如00123的真实值是123)
while (digits.size() > 1 && digits.back() == 0) {
digits.pop_back(); // 移除最高位的0
}
}
public:
// 构造函数:支持从字符串构造大整数
BigInt(const string& num = "0") {
if (num.empty()) { // 处理空字符串特殊情况
digits = {0}; // 初始化为0
return;
}
// 从字符串末尾开始解析(个位在前),例如"123"存储为[3,2,1]
for (int i = num.size() - 1; i >= 0; --i) {
if (!isdigit(num[i])) // 确保字符是数字(原代码缺少校验,建议添加)
throw invalid_argument("Invalid character in number string");
digits.push_back(num[i] - '0'); // 将字符转换为整型数字
}
trimLeadingZeros(); // 清除前导零(如"000"转为0)
}
// 加法运算符重载(核心算法)
BigInt operator+(const BigInt& other) const {
BigInt result;
result.digits.clear(); // 清空初始的0
int carry = 0; // 进位值,初始为0
// 遍历所有位数直到处理完所有数字且没有进位
for (size_t i = 0;
i < max(digits.size(), other.digits.size()) || carry;
++i)
{
int sum = carry; // 当前位总和初始化为进位值
// 加当前对象的第i位(如果存在)
if (i < digits.size()) sum += digits[i];
// 加另一个对象的第i位(如果存在)
if (i < other.digits.size()) sum += other.digits[i];
result.digits.push_back(sum % 10); // 取个位存入结果
carry = sum / 10; // 计算新的进位值(0或1)
}
return result;
}
// 输出运算符重载(将存储的逆序数字转回正常顺序)
friend ostream& operator<<(ostream& os, const BigInt& num) {
// 从最高位开始输出(digits最后一位是最高位)
for (int i = num.digits.size() - 1; i >= 0; --i) {
os << num.digits[i]; // 逐位输出数字字符
}
return os;
}
// 输入运算符重载(读取字符串并构造对象)
friend istream& operator>>(istream& is, BigInt& num) {
string input;
is >> input; // 从输入流读取字符串
num = BigInt(input); // 调用构造函数创建新对象
return is;
}
};
int main() {
BigInt a, b;
cin >> a >> b;
cout << a + b << endl;
}