题目地址:
https://www.acwing.com/problem/content/794/
给定两个正整数,算其差。结果可能是负数。
输入格式:
共两行,每行包含一个整数。
输出格式:
共一行,包含所求的差。
数据范围:
1
≤
l
≤
100000
1\le l\le 100000
1≤l≤100000
l
l
l是整数的长度
高精度减法。由于可能会减成负数,我们先判断一下哪个大,然后写一个大减小的函数,最后输出的时候,根据情况前面加负号。代码如下:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
// 返回a是否大于等于b
bool cmp(auto& a, auto& b) {
if (a.size() != b.size()) return a.size() >= b.size();
return a >= b;
}
string sub(auto& a, auto& b) {
string c;
c.reserve(a.size());
for (int i = 0, t = 0; i < a.size(); ++i) {
int x = a[a.size() - 1 - i] - '0';
int y = (i < b.size() ? b[b.size() - 1 - i] - '0' : 0);
int diff = x - y - t;
if (diff < 0) {
diff += 10;
t = 1;
} else
t = 0;
c += diff + '0';
}
while (c.size() > 1 && c.back() == '0') c.pop_back();
reverse(c.begin(), c.end());
return c;
}
int main() {
string a, b;
getline(cin, a);
getline(cin, b);
cout << (cmp(a, b) ? sub(a, b) : "-" + sub(b, a)) << endl;
}
时空复杂度 O ( l ) O(l) O(l)。