高精度减

P2142 高精度减法

题目描述

高精度减法。

输入格式

两个整数 \(a,b\)(第二个可能比第一个大)。

输出格式

结果(是负数要输出负号)。

输入输出样例 #1

输入 #1

2
1

输出 #1

1

说明/提示

  • \(20\%\) 数据 \(a,b\) 在 long long 范围内;
  • \(100\%\) 数据 \(0<a,b\le 10^{10086}\)

AC代码

#include<bits/stdc++.h>
using namespace std;

bool compare(string a,string b){
    if(a.size()<b.size()) return true;
    if(a.size()>b.size()) return false;
    for(int i=0;i<a.size();i++){
        if(a[i]>b[i]) return false;
        if(a[i]<b[i]) return true;
    }
    return false;
}

string gsub(string a,string b){
    int flag=1;
    string c="";
    if (compare(a, b))
    {
        swap(a, b);
        flag=0;
    }
    while (b.size() < a.size())
        b = '0' + b;
    int jw = 0, t1, t2, t;
    char ch;
    for (int i = a.size() - 1; i >= 0; i--)
    {
        t1 = a[i] - '0', t2 = b[i] - '0';
        if (t1 - jw < t2)
        {
            t = t1 + 10 - jw - t2;
            jw = 1;
        }
        else
        {
            t = t1 - jw - t2;
            jw=0;
        }
        ch = '0' + t;
        c = ch + c;
    }
    t=0;
    while(c[t]=='0'&&c.size()!=1){
        c.erase(c.begin());
    }
    if(flag==0&&c!="0") c='-'+c;
    return c;
}

int main(){
    string a,b;
    cin>>a>>b;
    cout<<gsub(a,b);
    return 0;
}
posted @ 2025-11-12 09:11  sadmax11  阅读(4)  评论(0)    收藏  举报