Jankeyfu
Jankeyfu

Reputation: 29

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.

/**
 * 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);
    }
}

Upvotes: 1

Views: 711

Answers (3)

Mellow
Mellow

Reputation: 1

I think the issue here is when you keep calling the code over and over, I tried it with a do loop instead:

 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);
}

}

Yours was returning the value back to where it had called it over and over not back to main until like the 3rd or 4th time.

Upvotes: 0

janos
janos

Reputation: 124704

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;
}
return addDigits(sum);

Upvotes: 1

Jerry Chin
Jerry Chin

Reputation: 667

That's because you forgot to capture the return value from every invocation to addDigits(), replace your code with the following line:

 tempInt = addDigits(tempInt);

Upvotes: 1

Related Questions