0

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. but my function returns 11 ? what is wrong with my logic? Help !!

public class Solution {
    public int addDigits(int num) {
    int result=doSum(num);
    return result;
    }

    public static int doSum(int num){
        int sum=0,digit;
        while(num!=0){
            digit=num%10;
            sum+=digit;
            num=num/10;
        }
        if(sum/10!=0){
            doSum(sum);
        }
        return sum;
    }
}
2
  • Show your main function also. Commented Sep 22, 2015 at 7:34
  • 4
    you need to say return doSum(sum); Commented Sep 22, 2015 at 7:34

1 Answer 1

5
if(sum/10!=0){
    doSum(sum);
}

This is what is wrong with your logic. You recursively call doSum() on the new sum but you do nothing with the result. So you need to change this to:

if(sum/10!=0){
   sum = doSum(sum);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.