题解,亲测可过(有批注)
2026-09-06 11:41:54
发布于:上海
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// 将较短的字符串高位补齐相同长度,同时将这个字符串转变为整数
void FIX(string& s, int length) {
reverse(s.begin(), s.end());
while (s.length() != length) {
s.push_back('0');
}
for (int i = 0; i < s.size(); i++) {
s[i] -= '0';
}
}
// 将高位 '0' 删除,最终反转
void RESULT(string& s) {
while (s.size() > 1 && s.back() == '0') s.pop_back();
reverse(s.begin(), s.end());
}
int main() {
string a,b;
cin>>a>>b;
int length=max(a.size(),b.size());
bool neg=false;
if(a<b&&a.size()b.size()||a.size()<b.size()){
neg=true;
swap(a,b);
}
// 两个数字相减的结果,位数最多不超过 a, b 两数最长位数
string c(length,0);
// 字符串反转,方便相减退位,同时变为整数
FIX(a,length);
FIX(b,length);
for(int i=0; i<a.size(); i++){
c[i] += a[i] - b[i];
if(c[i] < 0){
c[i+1] -= 1;
c[i] += 10;
}
c[i] += 48;
}
RESULT(c);
if(neg1) cout<<'-';
cout<<c;
return 0;
}
这里空空如也







有帮助,赞一个