首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BigInt减法

BigInt减法
EN

Stack Overflow用户
提问于 2017-01-09 11:23:26
回答 1查看 500关注 0票数 0

我在Java中尝试用carrys减法时遇到了一个问题。

代码语言:javascript
复制
public BigInt add(BigInt o) {
    int carry = 0;
    int max = n.length > o.n.length ? n.length : o.n.length;
    int[] result = new int[max+1];

    for (int i = 0; i <= max; ++i) {
        int top = i < n.length ? n[i] : 0;
        int bot = i < o.n.length ? o.n[i] : 0;

        result[i] = (top + bot + carry) % 10;
        carry = (top + bot + carry) / 10;
    }

    return new BigInt(trim(result));
}

public BigInt sub(BigInt o) {
    int carry = 0;
    int max = n.length > o.n.length ? n.length : o.n.length;
    int[] result = new int[max+1];

    for (int i = 0; i <= max; ++i) {

        int top = i < n.length ? n[i] : 0;
        int bot = i < o.n.length ? o.n[i] : 0;

        carry = (top + bot + carry) / 10;
        result[i] = (10 + top - bot - carry) % 10;
    }

    return new BigInt(trim(result));
}

我不知道我做错了什么?我的加法类工作得很好,但减法给了我一个奇怪的答案。假设我减去5943-3952,得到2091。当我们知道答案是1991年。我所有的答案都是错误的,只有前两位数不正确。救命!

EN

回答 1

Stack Overflow用户

发布于 2017-01-11 19:26:45

你的代码有很多错误,但首先要做的就是让你得到想要的结果:

代码语言:javascript
复制
public BigInt sub(BigInt o) 
{
    int carry = 0;
    int max = n.length > o.n.length ? n.length : o.n.length;
    int[] result = new int[max+1];

    for (int i = 0; i <= max; ++i) 
    {
        int top = i < n.length ? n[i] : 0;
        int bot = i < o.n.length ? o.n[i] : 0;

        int res = top - bot - carry;

        result[i] = (10 + res) % 10;
        carry = res < 0 ? 1 : 0;
    }

    return new BigInt(trim(result));
}   

但是,请注意,您没有考虑到左操作数可能比右操作数小的事实,因此您将得到负结果。在将BigInt表示为“数字”数组时,似乎没有一种方法来表示负值。如果有的话,我看不出来。

如果你也有负值,有四种情况:

结果正-正:总是从最高值中减去最低值(总是38 - 17,而不是17 - 38),相应地调整符号(例如17 - 38 38 - 17 = 21,现在调整符号,因为第一个是最小的:

  • -21)。请注意,您需要一个函数来比较幅度(即数组中的值,而不考虑符号)。
  • positive - negative:将幅值(数组)相加,符号为正(例如17 - (- 38 ) = 17 +38=55。
  • negative - positive:将幅值相加,符号为负。(例如-17 - (+ 38 ) = -17 -38= -(17 + 38) =-55。
  • negative- negative:作为第一种情况,相应地调整符号。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41540556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档