对于20位以上的超长整数无法用int、long等基本类型表示,但可以考虑用字符串实现。 本关任务:编写程序,基于字符串实现对超长整数的加法运算和减法运算,输入两个超长整数和运算符(+或-),输出运算结果。include <iostream> #include <cstring> using namespace std;
时间: 2024-03-10 15:46:01 浏览: 22
好的,我可以帮你实现这个功能。我们可以使用字符串代替超长整数进行运算,具体实现方法和前面的示例类似,也是逐位相加或逐位相减,并考虑进位和借位的情况。下面是一个简单的实现示例,你可以根据自己的需求进行修改和优化。
```
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string add(string num1, string num2) {
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int len1 = num1.size(), len2 = num2.size();
int len = max(len1, len2);
int carry = 0;
string res = "";
for (int i = 0; i < len; i++) {
int x = i < len1 ? num1[i] - '0' : 0;
int y = i < len2 ? num2[i] - '0' : 0;
int sum = x + y + carry;
res += to_string(sum % 10);
carry = sum / 10;
}
if (carry) res += to_string(carry);
reverse(res.begin(), res.end());
return res;
}
string sub(string num1, string num2) {
if (num1 == num2) return "0";
bool neg = false;
if (num1.size() < num2.size() || (num1.size() == num2.size() && num1 < num2)) {
swap(num1, num2);
neg = true;
}
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int len1 = num1.size(), len2 = num2.size();
int len = max(len1, len2);
int carry = 0;
string res = "";
for (int i = 0; i < len; i++) {
int x = i < len1 ? num1[i] - '0' : 0;
int y = i < len2 ? num2[i] - '0' : 0;
int diff = x - y - carry;
if (diff < 0) {
diff += 10;
carry = 1;
} else {
carry = 0;
}
res += to_string(diff);
}
reverse(res.begin(), res.end());
while (res.size() > 1 && res[0] == '0') {
res.erase(0, 1);
}
return neg ? "-" + res : res;
}
int main() {
string num1, num2, op;
cin >> num1 >> op >> num2;
if (op == "+") {
cout << add(num1, num2) << endl;
} else if (op == "-") {
cout << sub(num1, num2) << endl;
} else {
cout << "Invalid operator" << endl;
}
return 0;
}
```