P1303 A*B Problem(高精)
算法分类:高精度运算
链接:洛谷OJ
P1303 A*B Problem
题目背景
高精度乘法模板题。
题目描述
给出两个非负整数,求它们的乘积。
输入格式
输入共两行,每行一个非负整数。
输出格式
输出一个非负整数表示乘积。
输入输出样例 #1
输入 #1
1
2
输出 #1
2
说明/提示
每个非负整数不超过 1 0 2000 10^{2000} 102000。
题解
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class BigInt {
private:
vector<int> digits;
void trimLeadingZeros() {
while (digits.size() > 1 && digits.back() == 0) {
digits.pop_back();
}
}
public:
BigInt(const string& num = "0") {
if (num.empty()) {
digits = {0};
return;
}
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();
}
// 加法运算符重载(核心算法)
BigInt operator+(const BigInt& other) const {
BigInt result;
result.digits.clear();
int carry = 0;
for (size_t i = 0;
i < max(digits.size(), other.digits.size()) || carry;
++i)
{
int sum = carry;
if (i < digits.size()) sum += digits[i];
if (i < other.digits.size()) sum += other.digits[i];
result.digits.push_back(sum % 10);
carry = sum / 10;
}
return result;
}
// 输出运算符重载(将存储的逆序数字转回正常顺序)
friend ostream& operator<<(ostream& os, const BigInt& num) {
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;
}
// 乘法运算符重载(核心算法)
BigInt operator*(const BigInt& other) const {
BigInt result; // 创建结果对象
// 预分配结果数组空间(两数位数之和,确保足够存储所有位数)
result.digits.resize(digits.size() + other.digits.size(), 0);
// 外层循环:遍历乘数的每一位(当前对象的每个digit)
for (size_t i = 0; i < digits.size(); ++i) {
int carry = 0; // 当前位的进位值
// 内层循环:遍历被乘数的每一位(other对象的digit)或处理剩余进位
for (size_t j = 0; j < other.digits.size() || carry; ++j) {
// 计算当前位的乘积总和:
// 1. 当前结果位已有的值(来自之前的计算)
// 2. 当前乘数位 × 被乘数位(如果存在)
// 3. 来自前一位的进位
long long product = result.digits[i + j] +
digits[i] * (j < other.digits.size() ? other.digits[j] : 0) +
carry;
// 更新当前结果位:取个位数
result.digits[i + j] = product % 10;
// 计算新的进位:取十位数(自动向下取整)
carry = product / 10;
}
}
// 去除结果中的前导零(例如 0 × 123 = 000 转换为 0)
result.trimLeadingZeros();
return result;
}
};
// 更新主函数测试乘法
int main() {
BigInt a, b;
cin >> a >> b;
cout << a*b << endl;
return 0;
}
1868

被折叠的 条评论
为什么被折叠?



