AcWing 792. 高精度减法--string加哨兵 C++
原题链接
简单
作者:
I+III
,
2021-05-28 12:59:41
,
所有人可见
,
阅读 211
#include<bits/stdc++.h>
using namespace std;
//当a,b长度相同时,判断a是否小于b
bool judge(string a, string b){
int i = 0, n = a.size();
while(i < n){
int num1 = a[i] - '0', num2 = b[i] - '0';
if(num1 < num2) return true;
else if(num1 == num2) i++;
else if(num1 > num2) return false;
}
return false;
}
int main(){
string a, b;
cin>>a>>b;
bool flag = 0;
//使a大于等于b
if(a.size() < b.size() || (a.size() == b.size() && judge(a, b))){
string temp = a;
a = b;
b = temp;
flag = 1;
}
int n = a.size(), m = b.size();
for(int i = 0; i < n-m; i++){
b = " " + b;
}
for(int i = n-1, carry = 0; i >= 0; i--){
int num1 = (a[i] != ' ') ? a[i] - '0' : 0;
int num2 = (b[i] != ' ') ? b[i] - '0' : 0;
int num = num1 - num2 - carry;
a[i] = (num + 10) % 10 + '0';
carry = num < 0 ? 1 : 0;
}
while(a.size() > 1 && a[0] == '0') a.erase(0, 1);
if(flag) a = "-" + a;
cout<<a<<endl;
return 0;
}