跳到正文

个人记录

高精全家桶 (全文背诵并默写)

FLY_lai约 6 分钟
原文

这是 2025年10月23日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月26日
篇幅
约 6 分钟

版本

  1. v2当前
  2. v1
C++
#include <iostream>
#include <vector>
#include <string>
using namespace std;

struct BigInt {
	vector<int> d;//记录数的每一位,d[i]为10^i项
	BigInt() {
		d.clear();
	}
	BigInt(int x) {
		while (x) {
			d.push_back(x % 10);
			x /= 10;
		}
	}
}; 

//输入 
istream& operator>>(istream& _cin, BigInt &x) {
	string s;
	_cin >> s;
	x.d.assign(s.size(), 0);
	for (int i = 0; i < s.size(); i++)
		x.d[i] = (s[(s.size() - 1) - i] - '0');
	return _cin;
}

//输出 
ostream& operator<<(ostream& _cout, const BigInt &x) {
	for (int i = x.d.size() - 1; i >= 0; i--)
		_cout << x.d[i];
	return _cout;
}

bool operator<(BigInt x, BigInt y) {
	if (x.d.size() != y.d.size())//位数不同,比位数 
		return x.d.size() < y.d.size();
	for (int i = x.d.size() - 1; i >= 0; i--)//否则从最高尾开始比
		if (x.d[i] != y.d[i]) 
			return x.d[i] < y.d[i];
	return false;//相等不是小于 
}

bool operator>(BigInt x, BigInt y) {
	return y < x;
}

bool operator>=(BigInt x, BigInt y) {
	return !(x < y);
}

bool operator<=(BigInt x, BigInt y) {
	return !(x > y);
}

//加法 
BigInt operator+(BigInt x, BigInt y) {
	if (x.d.size() < y.d.size())
		return y + x;
	BigInt ans;
	ans.d.assign(x.d.size() + 1, 0);//ans.d重新赋值,长度是位数较大的那个的位数加一 
	//注意 +1,例如 三位 + 三位 <= 四位,和的位数不会超过位数较大的位数+1 
	for (int i = 0; i < x.d.size(); i++)
		ans.d[i] += x.d[i];
	for (int i = 0; i < y.d.size(); i++)
		ans.d[i] += y.d[i];
	for (int i = 0; i < ans.d.size() - 1; i++)
		ans.d[i + 1] += ans.d[i] / 10, ans.d[i] %= 10;
	if (ans.d[ans.d.size() - 1] == 0)//因为一开始加了一位,如果两数相加没有再多一位,就要去除前导零 
		ans.d.pop_back();
	return ans;
} 

//绝对值版本的减法 
BigInt operator-(BigInt x, BigInt y) {
	if (x < y)
		return y - x;
	BigInt ans;
	ans.d.assign(x.d.size(), 0);
	for (int i = 0; i < x.d.size(); i++)
		ans.d[i] += x.d[i];
	for (int i = 0; i < y.d.size(); i++)
		ans.d[i] -= y.d[i];
	for (int i = 0; i < ans.d.size(); i++)
		if (ans.d[i] < 0) {
			ans.d[i + 1]--;
			ans.d[i] = 10 + ans.d[i];
		}
	for (int i = ans.d.size() - 1; i >= 0; i--)
		if (ans.d[i] == 0)
			ans.d.pop_back();
		else
			break;
	return ans;
}

//乘法 
BigInt operator*(BigInt x, BigInt y) {
	BigInt ans;
	ans.d.assign(x.d.size() + y.d.size(), 0);
	for (int i = 0; i < x.d.size(); i++) {
		for (int j = 0; j < y.d.size(); j++)
			ans.d[i + j] += x.d[i] * y.d[j];
	}
	for (int i = 0; i < ans.d.size(); i++) {
		ans.d[i + 1] += ans.d[i] / 10;
		ans.d[i] %= 10;
	}
	for (int i = ans.d.size() - 1; i >= 1; i--)
		if (ans.d[i] == 0)
			ans.d.pop_back();
		else
			break;
	return ans;
}

//带余除法的商 
BigInt operator/(BigInt x, BigInt y) {
	BigInt ans;
	BigInt one(1), zero(0), ten(10);
	while (x >= y) {
		BigInt t = y, temp = t * ten, tt(1);
		while (temp <= x) {
			temp = temp * ten;
			t = t * ten;
			tt = tt * ten;
		}
		x = x - t;
		ans = ans + tt;
	}
	return ans;
} 

//带余除法的余数
BigInt operator%(BigInt x, BigInt y) {
	return x - (x / y) * y;
} 

int main()
{
	
	return 0;
}