通过添加和减去32位数字来避免StackOverflowError

时间:2017-03-27 15:47:12

标签: java recursion stack-overflow

我似乎无法使用我的最新代码绊倒一些递归问题。我正在添加和减去32位数的自定义数字。数字存储在一个数组中。

这里有一些代码来说明我的问题:

    public Custom subtract(Custom e) {
     if (isPositive(this) && (!isPositive(e))) {
         return add(temp);
    }   

在add方法中:

      if (isPositive(this)) {
            if (!isPositive(e)) {
                if (this.e.array.length >= e2.array.length) {
                    return subtract(e);

问题是,长度将始终保持不变,并且对于传入的参数,符号也将始终为常量。我认为我最好的选择是复制每个自定义对象并更改符号以满足加或减,但这样做会覆盖现有的正确值。有没有人有任何建议?

1 个答案:

答案 0 :(得分:0)

尝试:

public Custom subtract(Custom e) {
 if (isPositive(this) && (!isPositive(e))) {
     Custom temp = new Custom(negate(e));
     return add(temp);
}

negate()返回其参数并翻转符号。