算法理解
先比较绝对值,较小的数放到减数位置;反转后逐位相减,不够减时向高位借 1。最后清除前导零并按比较结果决定负号。
- 复杂度:
O(max(n, m))。 - 注意:
0 - 0仍应输出一个0,不能清空整个字符串。
模板代码
#include <bits/stdc++.h>
using namespace std;
bool cmp(string a, string b)
{
if (a.size()!=b.size()) return a.size()>b.size();
for (int i=0;i<a.size();i++)
{
if (a[i]!=b[i]) return a[i]>b[i];
}
return true;
}
void dlt(string *c)
{
while ((*c).back()=='0' && (*c).size()>1)
{
(*c).pop_back();
}
}
int main()
{
int fuhao=0;
string a,b;
cin>>a>>b;
string c;
if (cmp(a,b)==false)
{
swap(a,b);
fuhao=1;
}
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int max_length = max(a.size(), b.size());
int last = 0;
for (int i=0;i<max_length;i++)
{
int t = (a[i]-'0') + last;
if (i < b.size()) t -= (b[i]-'0');
if (t < 0)
{
t += 10;
last = -1;
}
else last = 0;
c += t + '0';
}
dlt(&c);
reverse(c.begin(), c.end());
if (fuhao) cout << "-";
cout << c;
return 0;
}
