w2-4 高精度减法

发布时间 2023-04-19 21:12:13作者: lijunjie03
#include <iostream>
#include <string>

using namespace std;
int sum[50000];
int main()
{
    string a,b;
    long long x,y;
    cin>>a>>b;
    int jug=0,pd=0;
    if((a < b && a.size() == b.size()) || a.size() < b.size())//the key point, change the positive number to the negative number
    {
        swap(a, b);
        pd = 1;
    }
    x=a.length();
    y=b.length();
    for(long long i=0;i<x;++i){//specially,if(a=b),print"0"
        if(a[i]!=b[i]) jug=1;
    }
    if(!jug) cout<<'0';
    for(long long i=0;i<x;i++) sum[x-i-1]+=a[i]-'0';
    for(long long i=0;i<y;i++) sum[y-1-i]-=b[i]-'0';
    long long len=max(x,y);//len不精准但一定够大
    for(long long i=0;i<len;i++){
        if(sum[i]<0){//处理退位
            sum[i+1]--;
            sum[i]+=10;
        }
    }
    int judge=0;
    if(pd) cout<<'-';//负数加符号
    for(long long i=0;i<len;i++){//erase the extra zero
        if(sum[len-i-1]||judge){
            cout<<sum[len-i-1];一旦有非0了说明后面的0就可以输出
            judge=1;
        }
    }
    return 0;
}