用string类型完成大整数运算
时间: 2023-08-04 17:24:42 浏览: 91
使用 `string` 类型可以完成大整数运算。具体实现方法是将大整数存储在 `string` 类型中,然后通过模拟手算的方法进行加减乘除等运算。
以下是使用 `string` 类型进行大整数加法、减法、乘法和除法的示例代码:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// 大整数加法
string add(string num1, string num2) {
string res;
int carry = 0;
int i = num1.size() - 1, j = num2.size() - 1;
while (i >= 0 || j >= 0 || carry) {
int x = i >= 0 ? num1[i--] - '0' : 0;
int y = j >= 0 ? num2[j--] - '0' : 0;
int sum = x + y + carry;
res += to_string(sum % 10);
carry = sum / 10;
}
reverse(res.begin(), res.end());
return res;
}
// 大整数减法
string sub(string num1, string num2) {
string res;
int borrow = 0;
int i = num1.size() - 1, j = num2.size() - 1;
while (i >= 0 || j >= 0) {
int x = i >= 0 ? num1[i--] - '0' : 0;
int y = j >= 0 ? num2[j--] - '0' : 0;
int diff = x - y - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
res += to_string(diff);
}
reverse(res.begin(), res.end());
while (res.size() > 1 && res[0] == '0') {
res.erase(0, 1);
}
return res;
}
// 大整数乘法
string multiply(string num1, string num2) {
string res(num1.size() + num2.size(), '0');
for (int i = num1.size() - 1; i >= 0; --i) {
int carry = 0;
for (int j = num2.size() - 1; j >= 0; --j) {
int sum = (num1[i] - '0') * (num2[j] - '0') + (res[i + j + 1] - '0') + carry;
res[i + j + 1] = sum % 10 + '0';
carry = sum / 10;
}
res[i] += carry;
}
while (res.size() > 1 && res[0] == '0') {
res.erase(0, 1);
}
return res;
}
// 大整数除法
string divide(string num1, string num2) {
if (num2 == "0") {
return "NaN";
}
if (num1 == "0") {
return "0";
}
string res;
string remainder = num1.substr(0, num2.size() - 1);
for (int i = num2.size() - 1; i < num1.size(); ++i) {
remainder += num1[i];
int quotient = 0;
while (remainder >= num2) {
remainder = sub(remainder, num2);
quotient++;
}
res += to_string(quotient);
}
while (res.size() > 1 && res[0] == '0') {
res.erase(0, 1);
}
return res;
}
int main() {
string num1 = "12345678901234567890";
string num2 = "98765432109876543210";
// 加法
string sum = add(num1, num2);
cout << "num1 + num2 = " << sum << endl;
// 减法
string diff = sub(num1, num2);
cout << "num1 - num2 = " << diff << endl;
// 乘法
string product = multiply(num1, num2);
cout << "num1 * num2 = " << product << endl;
// 除法
string quotient = divide(num1, num2);
cout << "num1 / num2 = " << quotient << endl;
return 0;
}
```
上述代码中,`add`、`sub`、`multiply`、`divide` 分别对应大整数加法、减法、乘法和除法。这些函数的实现原理都是通过模拟手算的方法进行计算。
阅读全文