采用字符串实现正整数的高精度减法A-B,代码功能有限,注意A、B均大等于0,且A大等于B
具体代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
int to_Int(char c){
return (int)c-48;
}
char to_Char(int i){
return (char)i+48;
}
int main() {
string s1,s2,ans;
int t;
cin>>t;
while(t--){
// p表示当前位置,b表示借位
int p=0,b=0;
ans="";
cin>>s1>>s2;
// 反转字符串方便计算
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
int len1 = s1.length(), len2 = s2.length();
if(s1 == s2){
cout<<0<<endl;
continue;
}
while(p<len1){
if(p>=len2){
int x=to_Int(s1[p]);
if(b == 1){
if(x==0)
x=9;
else{
x-=1;
b=0;
}
}
ans+=to_Char(x);
p++;
continue;
}
int x= to_Int(s1[p]), y=to_Int(s2[p]);
if(b == 1){
if(x==0)
x=9;
else{
x-=1;
b=0;
}
}
if(x<y){
b = 1;
x+=10;
}
ans+=to_Char(x-y);
p++;
}
while(ans[ans.length()-1]=='0'){
ans = ans.substr(0,ans.length()-1);
}
reverse(ans.begin(), ans.end());
cout<<ans<<endl;
}
}