东方博宜OJ 1947:高精度减法4 ← 高精度加法+高精度减法

​【题目来源】
https://oj.czos.cn/p/1947

【题目描述】
做减法。

【输入格式】
输入:两个整数a,b(a,b均为长度不超过300位的整数,注意输入的整数可能是负数)。

【输出格式】
输出:一个整数,表示两数的差(从个位开始,每隔三位加一个" ," 号)。​​​​​​​

【输入样例】
7777777 -29​​​​​​​

【输出样例】
7,777,806

【数据范围】
不超过300位的整数​​​​​​​

【算法分析】
注意负数。主体代码与 https://blog.csdn.net/hnjzsyjyj/article/details/166633763 一致。

【算法代码】

#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;
}

string add_comma(string s) {
    if(s=="0") return "0";
    bool st=(s[0]=='-');
    string t=st?s.substr(1):s;

    string res;
    int cnt=0;
    for(int i=t.size()-1; i>=0; i--) {
        res+=t[i];
        cnt++;
        if(cnt%3==0 && i!=0) res+=',';
    }
    reverse(res.begin(),res.end());
    return st?"-"+res:res;
}

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<<add_comma(ans)<<endl;
    return 0;
}

/*
in:7777777 -29
out:7,777,806
*/



【参考文献】
​​​​​​​
https://blog.csdn.net/hnjzsyjyj/article/details/166633763
https://blog.csdn.net/hnjzsyjyj/article/details/144703201
https://blog.csdn.net/hnjzsyjyj/article/details/144661288

​

posted @ 2026-09-25 20:19  Triwa  阅读(2)  评论(0)    收藏  举报