Joker - 1 year ago 90
Java Question

# how to understand the return value in java's recursion

I have coded a program with java languageļ¼but the answer is never the right one, I use the recursion to complete the program,but the return value in the method is not the one I want,it can be return twice when I debug it.if there anyone who can explain it for me ,Thanks a lot.

``````/**
* 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{
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]);
}
} else {
tempInt = num;
}
return tempInt;
}

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

When you call `addDigits(tempInt);` recursively inside your function, you're not doing anything with the result, you're just throwing it away. Changing the line to this will fix it:

``````tempInt = addDigits(tempInt);
``````

Also, you can solve this more elegantly and without converting to string:

``````if (num < 10) {
return num;
}

int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}