在C++的实际开发中,内置的int、long long等整数类型都有明确的数值范围,当需要处理超过这些范围的超长整数运算时,就需要自己实现高精度的数值计算类。我们可以通过字符串存储大数,再结合运算符重载实现各类运算,让自定义类的使用体验和内置数值类型一致。
类的整体设计
高精度数值计算类的核心是用字符串保存超长整数的每一位,同时需要记录数值的正负属性。我们定义类名为BigInteger,成员变量包含两个私有属性:一个字符串用于存储数值的绝对值,一个布尔值用于标记是否为负数。
成员变量与构造方法
构造方法需要支持从字符串和内置整数类型初始化,同时需要处理前导零和正负号的情况。具体实现代码如下:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
class BigInteger {
private:
string num; // 存储数值的绝对值,逆序存储方便运算
bool isNegative; // 标记是否为负数
// 去除前导零的辅助函数
void removeLeadingZeros() {
while (num.size() > 1 && num.back() == '0') {
num.pop_back();
}
}
public:
// 默认构造,初始化为0
BigInteger() : num("0"), isNegative(false) {}
// 从字符串构造
BigInteger(const string& s) {
if (s.empty()) {
num = "0";
isNegative = false;
return;
}
int start = 0;
if (s[0] == '-') {
isNegative = true;
start = 1;
} else {
isNegative = false;
}
// 跳过前导零
while (start < s.size() && s[start] == '0') {
start++;
}
if (start == s.size()) {
num = "0";
isNegative = false;
} else {
num = s.substr(start);
reverse(num.begin(), num.end()); // 逆序存储,低位在前
}
}
// 从long long构造
BigInteger(long long n) {
if (n < 0) {
isNegative = true;
n = -n;
} else {
isNegative = false;
}
if (n == 0) {
num = "0";
} else {
num.clear();
while (n > 0) {
num.push_back((n % 10) + '0');
n /= 10;
}
}
}
};
比较运算符重载
实现加减乘除运算前,需要先实现比较运算符,方便判断两个大数的大小关系。我们重载<、>、==等运算符,比较逻辑需要先判断正负,再比较绝对值大小。
// 重载==运算符
bool operator==(const BigInteger& other) const {
return num == other.num && isNegative == other.isNegative;
}
// 重载!=运算符
bool operator!=(const BigInteger& other) const {
return !(*this == other);
}
// 重载<运算符
bool operator<(const BigInteger& other) const {
// 正负不同的情况
if (isNegative != other.isNegative) {
return isNegative;
}
// 同正的情况
if (!isNegative) {
if (num.size() != other.num.size()) {
return num.size() < other.num.size();
}
// 位数相同,从高位到低位比较
string a = num, b = other.num;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
return a < b;
}
// 同负的情况,绝对值大的反而小
if (num.size() != other.num.size()) {
return num.size() > other.num.size();
}
string a = num, b = other.num;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
return a > b;
}
// 重载>运算符
bool operator>(const BigInteger& other) const {
return other < *this;
}
// 重载<=运算符
bool operator<=(const BigInteger& other) const {
return !(*this > other);
}
// 重载>=运算符
bool operator>=(const BigInteger& other) const {
return !(*this < other);
}
加法运算符重载
加法需要考虑两个大数同号和异号的情况,异号时实际是做减法运算。我们先将加法逻辑拆分为同号相加和异号相减的辅助函数,再在重载的+运算符中调用。
private:
// 两个非负大数相加,返回结果字符串(逆序)
static string addAbs(const string& a, const string& b) {
string res;
int carry = 0;
int i = 0, j = 0;
while (i < a.size() || j < b.size() || carry) {
int sum = carry;
if (i < a.size()) sum += a[i++] - '0';
if (j < b.size()) sum += b[j++] - '0';
res.push_back((sum % 10) + '0');
carry = sum / 10;
}
return res;
}
// 两个非负大数相减,a >= b,返回结果字符串(逆序)
static string subAbs(const string& a, const string& b) {
string res;
int borrow = 0;
int i = 0, j = 0;
while (i < a.size()) {
int diff = (a[i] - '0') - borrow;
if (j < b.size()) diff -= (b[j] - '0');
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
res.push_back(diff + '0');
i++;
j++;
}
// 去除结果中的前导零
while (res.size() > 1 && res.back() == '0') {
res.pop_back();
}
return res;
}
public:
// 重载+运算符
BigInteger operator+(const BigInteger& other) const {
BigInteger res;
if (isNegative == other.isNegative) {
// 同号,绝对值相加,符号不变
res.num = addAbs(num, other.num);
res.isNegative = isNegative;
} else {
// 异号,比较绝对值大小
BigInteger a = *this, b = other;
if (a.isNegative) {
a.isNegative = false;
b.isNegative = false;
if (a > b) {
res.num = subAbs(a.num, b.num);
res.isNegative = true;
} else {
res.num = subAbs(b.num, a.num);
res.isNegative = false;
}
} else {
b.isNegative = false;
if (*this >= other) {
res.num = subAbs(num, other.num);
res.isNegative = false;
} else {
res.num = subAbs(other.num, num);
res.isNegative = true;
}
}
}
res.removeLeadingZeros();
return res;
}
输出运算符重载
为了让BigInteger对象可以直接用cout输出,我们需要重载<<运算符,输出时先输出负号(如果是负数),再逆序输出存储的数值字符串。
// 重载输出运算符,需要声明为友元函数
friend ostream& operator<<(ostream& os, const BigInteger& bigInt) {
if (bigInt.isNegative) {
os << '-';
}
string tmp = bigInt.num;
reverse(tmp.begin(), tmp.end());
os << tmp;
return os;
}
使用示例
完成上述核心功能后,我们可以测试这个高精度类的使用效果,代码如下:
int main() {
BigInteger a("12345678901234567890");
BigInteger b("-98765432109876543210");
BigInteger c = a + b;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a + b = " << c << endl;
BigInteger d(12345);
BigInteger e("99999999999999999999");
BigInteger f = d + e;
cout << "d = " << d << endl;
cout << "e = " << e << endl;
cout << "d + e = " << f << endl;
return 0;
}
上述代码运行后,会正确输出超长整数的加法结果,证明了我们实现的高精度类的可用性。如果需要扩展减法、乘法、除法等运算,可以参考加法的实现思路,结合大数运算的常规算法补充对应的运算符重载即可。