AcWing 792. 高精度减法
原题链接
简单
作者:
Value
,
2020-04-25 18:17:05
,
所有人可见
,
阅读 421
方法一
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int compare(string a, string b){
if(a.size() > b.size()) return 1;
else if(a.size() < b.size()) return -1;
else{
for(int i = 0; i < a.size(); i ++ ){
if(a[i] > b[i]) return 1;
else if(a[i] < b[i]) return -1;
}
}
return 1;
}
string a, b;
int main(){
cin >> a >> b;
int flag = compare(a, b);
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
if(flag == -1){
cout << "-";
swap(a, b);
}
string res = "";
int cnt = 0;
int i;
for(i = 0; i < a.size() && i < b.size(); i ++ ){
int num = a[i] - b[i] - cnt;
if(num < 0){
num += 10;
cnt = 1;
}else cnt = 0;
res += (num + '0');
}
while(i < a.size()){
int num = a[i] - '0' - cnt;
if(num < 0){
num += 10;
cnt = 1;
}else cnt = 0;
res += (num + '0');
i ++ ;
}
reverse(res.begin(), res.end());
flag = 1;
for(int i = 0; i < res.size(); i ++ ){
if(flag == 1 && res[i] == '0'){
;
}else{
cout << res[i];
flag = 0;
}
}
if(flag == 1) cout << 0 << endl;
return 0;
}
方法二(精简版)
#include <iostream>
#include <vector>
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;
}
vector<int> sub(vector<int> &A, vector<int> &B){
vector<int> C;
int t = 0;
for(int i = 0; i < A.size(); i ++ ){
t = A[i] - t;
if(i < B.size()) t -= B[i];
C.push_back((t + 10) % 10);
if(t < 0) t = 1;
else t = 0;
}
while(C.size() > 1 && C.back() == 0) C.pop_back();
return C;
}
int main(){
string a, b; cin >> a >> b;
vector<int> A, B;
for(int i = a.size() - 1; i >= 0; i -- ) A.push_back(a[i] - '0');
for(int i = b.size() - 1; i >= 0; i -- ) B.push_back(b[i] - '0');
vector<int> C;
if(cmp(a, b)) C = sub(A, B);
else{
cout << "-";
C = sub(B, A);
}
for(int i = C.size() - 1; i >= 0; i -- ) cout << C[i];
return 0;
}