如何减去两个大数

时间:2019-03-08 04:30:35

标签: c++ math integer-arithmetic

我试图减去2个非常大的整数/大数,但是我遇到了一个问题。我的代码适用于123-94、5-29之类的减法运算,但我似乎无法解决边缘情况。例如13-15应该得到-2。但是,如果我在第一个数字上进行num1 - num2 - borrow + 10,则得到8,而borrow变为1。继续到最后一个数字,我得到的是1 - 1 - borrow(=1),因此剩下-1我的最终结果是-18,而不是-2

这是我的减法代码:


//Infint is the class for the very large number

Infint Infint::sub(Infint other)
{

    string result;

    Infint i1 = *this;
    Infint i2 = other;


    if (int(i1._numberstr.length() - i2._numberstr.length()) < 0)
    {
        Infint(result) = i2 - i1;
        result._numberstr.insert(result._numberstr.begin(), '-');
        return result;
    }

    else if (i1._numberstr.length() - i2._numberstr.length() > 0)
    {
        int diff = i1._numberstr.length() - i2._numberstr.length();
        for (int i = diff; i > 0 ; --i)
        {
            i2._numberstr.insert(i2._numberstr.begin(), '0');
        }
    }


    int borrow = 0;
    int i = i2._numberstr.length() - 1;
    for (; i >= 0 ; --i)
    {
        int sub = (i1._numberstr[i] - '0') - (i2._numberstr[i] - '0') - borrow;

        if (sub < 0)
        {
            sub += 10;
            borrow = 1;
        }

        else
            borrow = 0;

        result.insert(0, to_string(sub));
    }

    while (i > 0)
    {
        result.insert(result.begin(), i1._numberstr[i1._numberstr.length() - i]);
        --i;
    }

    int j = 0;
    while (result[j] == '0')
        j++;

    result.erase(0, j);

    if (borrow == 1)
        result.insert(result.begin(), '-');

    return Infint(result);
}

您能否请我理解我在逻辑上的错误或错误?

1 个答案:

答案 0 :(得分:0)

由于8位于1s位置,-1位于10s位置。这两个的总和是{em> -10 + 8 = -2(正确的答案(而不是-10 - 8 = -18,这是错误的))。

编辑:要系统地得出正确的答案,如果您发现最高的数字差为负,则将负号分配给所有数字。假设两个n位数字的位数差异为

a n-1 ,...,a 0

其中a j 是数字10 j 的差,您发现a n-1 <0。则总差两个数字中的一个可以计算为

-1 *(-a n-1 * 10 n-1 + ... + -a 0

通过从10 n-1 到1s的总和得出正确的(否定的)答案应该是相当简单的。