【题目来源】 https://oj.czos.cn/p/1946 【题目描述】 处理两个高精度数的减法。(1000位内) 【输入格式】 两行,每行一个整数。(可能为负数,负号用“-”表示) 【输出格式】 一个整数,即两个数相减的结果。 【输入样例】 2345678901234 123456789012345 【输出样例】 -121111110111111 【数据范围】 1000位内的整数。 【算法分析】 ● 注意:输入的数可能是负数! ● substr 函数的用法 (1)s.substr(i):从 i 开始,取到末尾。 (2)s.substr(i, k):从 i 开始,取 k 个字符。 【算法代码】
#include <bits/stdc++.h>
using namespace std;
string trim(string s) { //remove_leading_zero
int i=0;
while(i<s.size()-1 && s[i]=='0') i++;
return s.substr(i);
}
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; //a=b
}
string hiSub(string a,string b) {
string c;
int t=0;
int i=a.size()-1, j=b.size()-1;
while(i>=0 || j>=0) {
if(i>=0) t=(a[i]-'0')-t;
if(j>=0) t-=(b[j]-'0');
c+=((t+10)%10+'0');
t<0?t=1:t=0;
i–, j–;
}
while(c.size()>1 && c.back()=='0') c.pop_back();
reverse(c.begin(),c.end());
return c;
}
string hiAdd(string a,string b) {
string c;
int t=0;
int i=a.size()-1,j=b.size()-1;
while(i>=0 || j>=0) {
if(i>=0) t=(a[i]-'0')+t;
if(j>=0) t+=(b[j]-'0');
c+=(t%10+'0');
t/=10;
i–,j–;
}
if(t!=0) c+=(t+'0');
reverse(c.begin(),c.end());
return c;
}
int main() {
string s1,s2;
cin>>s1>>s2;
bool f1=(s1[0]=='-');
bool f2=(s2[0]=='-');
string a=trim(f1?s1.substr(1):s1);
string b=trim(f2?s2.substr(1):s2);
string ans;
if(!f1 && !f2) { //a-b
if(cmp(a,b)) ans=hiSub(a,b);
else ans="-"+hiSub(b,a);
} else if(!f1 && f2) { //a-(-b)=a+b
ans=hiAdd(a,b);
} else if(f1 && !f2) { //-a-b=-(a+b)
ans="-"+hiAdd(a,b);
} else { //-a-(-b)=b-a
if(cmp(b,a)) ans=hiSub(b,a);
else ans="-"+hiSub(a,b);
}
//eliminate -0
if(ans[0]=='-' && trim(ans.substr(1))=="0") ans="0";
cout<<ans<<endl;
return 0;
}
/*
in:
2345678901234
123456789012345
out:
-121111110111111
*/
【参考文献】 https://blog.csdn.net/hnjzsyjyj/article/details/144661288 https://blog.csdn.net/hnjzsyjyj/article/details/144703201
网硕互联帮助中心



评论前必须登录!
注册