@Yezi.press
bigInt 大整数及加法乘法模板
包含了 bigInt 大整数的结构体封装,加法、高精度*单精度乘法、高精度*高精度乘法重载(不考虑负数)
完整程序更新于 2026年8月20日 08:14#高精度
C++97 行2272 Bytes
#include <bits/stdc++.h>
using namespace std;
struct bigInt {
int digit[1000] = {0}, len = 0;
// s 的默认值为 “0”,可以不用传参
bigInt (string s = "0") {
len = s.size();
for (int i = 0, j = len-1; i < len; i++, j--)
digit[i] = s[j] - '0';
}
// 重载构造函数,支持传整数
bigInt (int n) {
// 处理传进来 0 的特殊情况
if (n == 0) len = 1;
while (n) {
digit[len++] = n % 10;
n /= 10;
}
}
void print() {
for (int i = len-1; i >= 0; i--)
cout << digit[i];
cout << endl;
}
};
bigInt operator+(bigInt a, bigInt b) {
bigInt c;
c.len = max(a.len, b.len);
for (int i = 0; i < c.len; i++) {
c.digit[i] += a.digit[i] + b.digit[i];
c.digit[i+1] += c.digit[i] / 10;
c.digit[i] %= 10;
}
if (c.digit[c.len]) c.len++;
return c;
}
// 仅支持 a >= b 的减法
bigInt operator-(bigInt a, bigInt b) {
bigInt c;
c.len = max(a.len, b.len);
for (int i = 0; i < c.len; i++) {
c.digit[i] += a.digit[i] - b.digit[i];
if (c.digit[i] < 0) {
c.digit[i] += 10;
c.digit[i+1]--;
}
}
while (c.len > 1 && c.digit[c.len-1] == 0) c.len--;
return c;
}
bigInt operator*(int a, bigInt b) {
for (int i = 0; i < b.len; i++)
b.digit[i] *= a;
for (int i = 0; i < b.len; i++) {
b.digit[i+1] += b.digit[i] / 10;
b.digit[i] %= 10;
}
while (b.digit[b.len]) {
b.len++;
b.digit[b.len] += b.digit[b.len-1] / 10;
b.digit[b.len-1] %= 10;
}
return b;
}
bigInt operator*(bigInt a, int b) {
return b * a;
}
bigInt operator*(bigInt a, bigInt b) {
bigInt c;
c.len = a.len + b.len - 1;
for (int i = 0; i < a.len; i++)
for (int j = 0; j < b.len; j++)
c.digit[i+j] += a.digit[i] * b.digit[j];
for (int i = 0; i < c.len; i++) {
c.digit[i+1] += c.digit[i] / 10;
c.digit[i] %= 10;
}
if (c.digit[c.len]) c.len++;
return c;
}
int main() {
string s1, s2;
cin >> s1 >> s2;
bigInt a = bigInt(s1) * bigInt(s2);
cout << a.len << endl;
a.print();
return 0;
}