大数相减

Give you two numbers A and B.

Your job is to calculator the result of A - B.

A, B is ranged from 0 ~ 10^100. (guarantee that A >= B)


Sample Input

3 2

1000000000000001 1

216360262764328698547112181349539426958555975 68359881780472809198305272

Sample Output

1

1000000000000000

216360262764328698478752299569066617760250703

code

#include 
#include 
using namespace std;

void process(string&a, string&b)
{
    int p[200] = { 0 };
    int q[200] = { 0 };
    int cura = 0,curb = 0;

    for (int i = a.length() - 1; i >= 0; i--)//复制a数组
    {
        p[cura] = a[i]-'0';
        cura++;
    }

    for (int i = b.length() - 1; i >= 0; i--)//复制b数组
    {
        q[curb] = b[i]-'0';
        curb++;
    }

    int cur = 0;

    while (cur < 199)//从末尾开始相减,并处理特殊情况
    {
        p[cur] -= q[cur];
        if (p[cur] < 0)
        {
            p[cur + 1]--;
            p[cur] += 10;
        }
        cur++;
    }

    for ( ; cur >= 0; cur--)//从头查找第一个不是0的数字
        if (p[cur] != 0) break;

    for ( ; cur >= 0; cur--)//从第一个不是0的数字开始打印
        cout << p[cur];

    cout << endl;
}

int main()
{
    string a, b;

    while (cin >> a >> b)
    {
        process(a, b);
    }

    return 0;
}

cpp文件在这里

你可能感兴趣的:(大数相减)