洛谷2142高精度减法(模板)

题目:https://www.luogu.org/problemnew/show/P2142

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char ch[10005];
int a[10005],b[10005],c[10005];
int comp(int a[],int b[])
{
    if(a[0]<b[0])return -1;
    if(a[0]>b[0])return 1;
    for(int i=a[0];i;i--)    ///别忘了倒序 
    {
        if(a[i]<b[i])return -1;
        if(a[i]>b[i])return 1;
    }
    return 0;
}
int main()
{
    cin>>ch;
    a[0]=strlen(ch);
    for(int i=1;i<=a[0];i++)a[i]=ch[a[0]-i]-'0';
    cin>>ch;
    b[0]=strlen(ch);
    for(int i=1;i<=b[0];i++)b[i]=ch[b[0]-i]-'0';
    if(comp(a,b)<0)
    {
        printf("-");
        memcpy(c,a,sizeof a);
        memcpy(a,b,sizeof b);
        memcpy(b,c,sizeof c);
        memset(c,0,sizeof c);
    }
    for(int i=1;i<=a[0];i++)////a[0]
    {
        c[i]=a[i]-b[i];
        if(c[i]<0)
        {
            c[i]+=10;a[i+1]--;
        }
    }
    c[0]=a[0];/////a[0]
    while(!c[c[0]]&&c[0]>1)c[0]--;
    for(int i=c[0];i;i--)printf("%d",c[i]);
    return 0;
}

 

posted on 2018-03-08 00:19  Narh  阅读(162)  评论(0编辑  收藏  举报

导航