我用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);
}
}
发布于 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);
发布于 2016-10-29 14:37:03
这是因为您忘记了捕获每个对addDigits()
的调用的返回值,请将您的代码替换为以下行:
tempInt = addDigits(tempInt);
发布于 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。
https://stackoverflow.com/questions/40316658
复制相似问题