怎样比较两个超长数字字符串的大小(两者均超过20位)
时间: 2024-03-08 10:50:33 浏览: 19
如果两个超长数字字符串均超过20位,则我们需要使用高精度计算的方法来比较它们的大小。
一种比较简单的方法是将两个字符串转换为两个高精度整数,然后进行比较。以下是一种实现方式:
1. 定义一个高精度整数类,可以参考以下代码:
```c++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class BigInt {
public:
BigInt() {}
BigInt(string s) {*this = s;}
BigInt operator = (string s) {
num.clear();
for (int i = s.size() - 1; i >= 0; i -= 9) {
int j = max(0, i - 8);
num.push_back(stoll(s.substr(j, i - j + 1)));
}
return *this;
}
BigInt operator + (BigInt &b) {
BigInt c;
c.num.clear();
for (int i = 0, g = 0; ; i++) {
if (g == 0 && i >= num.size() && i >= b.num.size()) break;
long long x = g;
if (i < num.size()) x += num[i];
if (i < b.num.size()) x += b.num[i];
c.num.push_back(x % 1000000000);
g = x / 1000000000;
}
return c;
}
bool operator < (const BigInt &b) const {
if (num.size() != b.num.size()) return num.size() < b.num.size();
for (int i = num.size() - 1; i >= 0; i--)
if (num[i] != b.num[i])
return num[i] < b.num[i];
return false;
}
bool operator == (const BigInt &b) const {
if (num.size() != b.num.size()) return false;
for (int i = 0; i < num.size(); i++)
if (num[i] != b.num[i])
return false;
return true;
}
private:
vector<long long> num;
};
```
2. 然后,我们可以将两个字符串转换为两个 BigInt 对象,并使用 “<” 和 “==” 运算符来比较它们的大小。以下是一段示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class BigInt {
// 定义 BigInt 类
// ...
};
int main() {
string s1 = "12345678901234567890";
string s2 = "98765432109876543210";
BigInt n1(s1);
BigInt n2(s2);
if (n1 < n2) {
cout << s1 << " < " << s2 << endl;
} else if (n1 == n2) {
cout << s1 << " = " << s2 << endl;
} else {
cout << s1 << " > " << s2 << endl;
}
return 0;
}
```
输出结果为:
```
12345678901234567890 < 98765432109876543210
```
这样,我们就可以比较两个超长数字字符串的大小了。