首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何理解java递归中的返回值

如何理解java递归中的返回值
EN

Stack Overflow用户
提问于 2016-10-29 14:26:01
回答 3查看 677关注 0票数 1

我用Java语言写了一个程序,但是结果从来都不是正确的,我使用递归来完成程序,但是方法中的返回值不是我想要的值,当我调试it.if的时候,它可以返回两次,有人可以给我解释一下,谢谢。

/**
 * addDigits:
 * Given a non-negative integer num * repeatedly add all 
 * its digits until the result has only one digit.
 * For example:
 * Given num = 38, the process is like: 
 * 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
 * it should be 2,but the answer is 11,may anyone help me with the problem?      
 * thanks
 */
public class Test{
    public int addDigits(int num) {
        String str = String.valueOf(num);
        String[] temp = new String[str.length()];
        int tempInt = 0;
        if (str.length() > 1) {
            for (int i = 0; i < str.length(); i++) {
                temp[i] = str.substring(i, i + 1);
                tempInt += Integer.parseInt(temp[i]);
            }
            addDigits(tempInt);
        } else {
            tempInt = num;
        }
        return tempInt;
}

    public static void main(String[] args) {
        Test test = new Test();
        int i = test.addDigits(38);
        System.out.println(i);
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-10-29 14:34:47

当您在函数中递归调用addDigits(tempInt);时,您并没有对结果做任何操作,而只是将其丢弃。将这一行更改为以下内容将会解决此问题:

tempInt = addDigits(tempInt);

此外,您可以更优雅地解决此问题,而无需转换为字符串:

if (num < 10) {
    return num;
}

int sum = 0;
while (num > 0) {
    sum += num % 10;
    num /= 10;
}
return addDigits(sum);
票数 1
EN

Stack Overflow用户

发布于 2016-10-29 14:37:03

这是因为您忘记了捕获每个对addDigits()的调用的返回值,请将您的代码替换为以下行:

 tempInt = addDigits(tempInt);
票数 1
EN

Stack Overflow用户

发布于 2016-10-29 14:50:50

我认为这里的问题是,当你一遍又一遍地调用代码时,我用do循环代替了它:

 public int addDigits(int num) {
   int tempInt;
   String str;

     do 
   {
        str = String.valueOf(num);
    String[] temp = new String[str.length()];
    tempInt = 0;
    if (str.length() > 1) {
        for (int i = 0; i < str.length(); i++) {
            temp[i] = str.substring(i, i + 1);
            tempInt += Integer.parseInt(temp[i]);
        }
        num = tempInt;
      } 
    } while (str.length() > 1);
   tempInt = num;
    return tempInt;

}

public static void main(String[] args) {
    Temp test = new Temp();
    int i = test.addDigits(38);
    System.out.println(i);
}

}

你一次又一次地将值返回到调用它的地方,直到第三次或第四次才返回到main。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40316658

复制
相关文章

相似问题

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