[高精度]高精减法

#include 
#include 
char s1[10100];
char s2[10100];
int a[10100];
int b[10100];
int main()
{
    int pp;scanf("%d",&pp);
    while (pp--)
    {
        scanf("%s%s",s1,s2);
        int l1 = strlen(s1);
        int l2 = strlen(s2);
        int flag = 0;

        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));  

        if ( l1 < l2 || (strcmp(s1,s2) < 0 && l1 == l2) )
        {
            flag = 1;
            for (int i = l2 - 1 ; i >= 0 ; i--)
                a[l2 - i - 1] = s2[i] - '0';
            for (int i = l1 - 1 ; i >= 0 ; i--)
                b[l1 - i - 1] = s1[i] - '0';
        }
        else
        {
            for (int i = l1 - 1 ; i >= 0 ; i--)
                a[l1 - i - 1] = s1[i] - '0';
            for (int i = l2 - 1 ; i >= 0 ; i--)
                b[l2 - i - 1] = s2[i] - '0';
        }
        int len;
        if (l1 > l2) 
            len = l1;
        else 
            len = l2;
//      for (int i = 0 ; i <= len ; i++)
//          a[i] = b[i] = 0;
        for (int i = 0 ; i < len ; i++)
        {
            a[i] = a[i] - b[i];
            if (a[i] < 0)
            {
                a[i+1]-=1;
                a[i]+=10;
            }
        }

        while (a[len - 1] == 0 && len>1) len--;

        if (flag == 1) printf("-");
        for (int i = len - 1 ;i >= 0 ;i--)
            printf("%d",a[i]);
        printf("\n");
    }
    return 0;
}

分段解读:
第一段:把字符串转换为整形数组(为了方便运算,倒序写入)
这里的fiag用于标记是否结果负数.并保证a中的数大于等于b

scanf("%s%s",s1,s2);
        int l1 = strlen(s1);
        int l2 = strlen(s2);
        int flag = 0;

        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));  

        if ( l1 < l2 || (strcmp(s1,s2) < 0 && l1 == l2) )
        {
            flag = 1;
            for (int i = l2 - 1 ; i >= 0 ; i--)
                a[l2 - i - 1] = s2[i] - '0';
            for (int i = l1 - 1 ; i >= 0 ; i--)
                b[l1 - i - 1] = s1[i] - '0';
        }
        else
        {
            for (int i = l1 - 1 ; i >= 0 ; i--)
                a[l1 - i - 1] = s1[i] - '0';
            for (int i = l2 - 1 ; i >= 0 ; i--)
                b[l2 - i - 1] = s2[i] - '0';
        }

第二段:把A和B中逐项相减.如果小于0则借位;

for (int i = 0 ; i < len ; i++)
        {
            a[i] = a[i] - b[i];
            if (a[i] < 0)
            {
                a[i+1]-=1;
                a[i]+=10;
            }
        }

第三段:while去首0

while (a[len - 1] == 0 && len>1) len--;

最后输出,如果有flag则输出’-‘

你可能感兴趣的:([高精度]高精减法)