美文网首页
大数相减

大数相减

作者: Icestains | 来源:发表于2017-05-12 17:24 被阅读0次

    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 <iostream>
    #include <string>
    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文件在这里

    相关文章

      网友评论

          本文标题:大数相减

          本文链接:https://www.haomeiwen.com/subject/voqtxxtx.html