在java中添加不带BigInt的负数和正数

在java中添加不带BigInt的负数和正数,java,if-statement,bignum,Java,If Statement,Bignum,我正在尝试编写一个小型java类。我有一个叫做BigNumber的对象。我写了两个正数相加的方法,以及另一个将两个正数相减的方法 现在我想让他们处理负数。因此,我写了两个“如果”语句,例如 if (this.sign == 1 /* means '+' */) { if (sn1.sign == 1) { if (this.compare(sn1) == -1 /* means this < sn1 */ ) return sn1.add(this);

我正在尝试编写一个小型java类。我有一个叫做BigNumber的对象。我写了两个正数相加的方法,以及另一个将两个正数相减的方法

现在我想让他们处理负数。因此,我写了两个“如果”语句,例如

if (this.sign == 1 /* means '+' */) {
    if (sn1.sign == 1) {
        if (this.compare(sn1) == -1 /* means this < sn1 */ ) return sn1.add(this);
        else return this.add(sn1);
    }

如您所见-此代码看起来很糟糕。

类似的内容可能更吸引人:

if (this.sign == 1 && sn1.sign == 1) {
    return (this.compare(sn1) < 0) ? sn1.add(this) : this.add(sn1);
}
if(this.sign==1&&sn1.sign==1){
返回(this.compare(sn1)<0)?sn1.add(this):this.add(sn1);
}

我建议你多花点时间;)这个怎么样:

if (isPositive() && other.isPositive()) {
  if (this.isBiggerThen(other)) {
    return this.plus(other);
  } else {
    return other.plus(this);
  }
}
请注意,我将sn1重命名为other,将
add
方法重命名为
plus
以指示该方法返回总和以增加可读性<代码>添加通常用于向对象本身添加内容(如在BigInteger类中)

isPositive和IsBigger的实现非常简单:

private boolean isPositive() {
  return sign == 1;
}

private boolean isBiggerThen(BigNumber other) {
  return this.compare(other) > 0;
}

你可以考虑使用补码算法。这将大大简化加法和减法。不必担心符号位,只需将数字相加。

有几件事让我困惑。不应该加是交换的。i、 e.对于a+b,其结果应与b+a相同

在大多数情况下,您只需确定符号是否相同即可添加绝对值

e、 g


为什么你不能在所有情况下都添加(sn1)?我打赌有一种更简单的方法来编写这个,但我认为我们可能需要一个更大的代码示例。这些线是用什么方法产生的?我不能这么做。加(sn1)因为有时候我想把正数加在负数上,或者把负数加在负数上。但是add只能处理正数。因此,我必须使用基本数学,例如:我将这个.abs()(数字的绝对值)添加到sn1.abs()中,并返回带相反符号的结果,而不是将负数添加到负数中。德鲁:这些线来自方法_add。我使用这个方法来决定如何处理它收到的数字。发送给他们添加方法?或者用不同的顺序(sn1.subtract(this))将它们发送到subract方法?等等..顺便说一下,您可以查找Java的
biginger
的源代码。另外,你也可以直接使用它。我已经阅读了BigInteger的代码,但是对于像我这样的初学者来说,它看起来太复杂了。谢谢-这看起来更糟糕。但有没有办法删除大部分if?如果你完全重写了它:也许吧。但是尝试将越来越多的代码提取到不同的方法中。这大大提高了可读性,并且您不必在单个方法中使用许多if-else构造。如果这只是为了提高你的技能-继续你开始的:)+1。编写add()方法以仅处理具有相同符号的值是liamg的第一个错误。加法和减法真的应该是相同的活动,就像用二的赞美法一样。谢谢你的回答。我曾考虑使用二进制数,但它看起来太“低级”了。但我从来没有听说过这些补码运算,我相信它在我的未来会很有用。
private boolean isPositive() {
  return sign == 1;
}

private boolean isBiggerThen(BigNumber other) {
  return this.compare(other) > 0;
}
if (sign == sn1.sign)
   return add(sn1);// add the absolute values and keep the sign. 1 + 1 == 2, -1 + -1 == -2
if (sign == 0) return sn1;
if (sn1.sign == 0) return this;
// you only need to know which value is larger for subtraction.
// keep the sign of the first argument and substract the absolute value.
return compare(sn1) > 0 ? substract(sn1) : sn1.substract(this);