只用string不用algorithm和vector實現高精度減法
时间: 2024-03-03 07:48:58 浏览: 20
可以使用字符串模拟高精度减法的过程,具体步骤如下:
1. 首先将两个数字转化为字符串形式,并确定两个数字的长度,假设它们分别为n和m。
2. 如果被减数小于减数,则将两个数字交换位置,并标记结果为负数。
3. 从两个数字的末尾开始,逐位相减,并将结果存储到一个新的字符串中。
4. 如果被减数的某一位小于减数的对应位,则需要向高位借位,直到两位数相减为正数。
5. 如果结果字符串的最高位为0,则需要去掉前导0。
6. 如果标记了结果为负数,则在结果字符串前面添加一个负号。
下面是一份高精度减法的示例代码,仅供参考:
```c++
#include <iostream>
#include <string>
using namespace std;
string subtract(string a, string b) {
int n = a.length(), m = b.length();
string res = "";
bool negative = false;
if (n < m) {
swap(a, b);
swap(n, m);
negative = true;
}
int i = n - 1, j = m - 1, carry = 0;
while (j >= 0) {
int x = a[i] - '0', y = b[j] - '0';
int diff = x - y - carry;
if (diff < 0) {
diff += 10;
carry = 1;
} else {
carry = 0;
}
res += to_string(diff);
i--;
j--;
}
while (i >= 0) {
int x = a[i] - '0';
int diff = x - carry;
if (diff < 0) {
diff += 10;
carry = 1;
} else {
carry = 0;
}
res += to_string(diff);
i--;
}
reverse(res.begin(), res.end());
while (res.length() > 1 && res[0] == '0') {
res.erase(res.begin());
}
if (negative) {
res = "-" + res;
}
return res;
}
int main() {
string a, b;
cin >> a >> b;
string res = subtract(a, b);
cout << res << endl;
return 0;
}
```