LeetCode – Add Digits (Java)

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.

Java Solution 1 - Recusion

public int addDigits(int num) {
    int sum=0;
 
    String s = String.valueOf(num);
    for(int i=0; i<s.length(); i++){
        sum = sum + (s.charAt(i)-'0');
    }
 
    if(sum < 10){
        return sum;
    }else{
        return addDigits(sum);
    }
}

Java Solution 2 - Math

public int addDigits(int num) {
    return num - 9*((num-1)/9);
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Peeyush Chandel

    Loop Solution:

    public int addDigits(int num) {
    int answer = helper(num);
    while((answer/10)!=0){
    answer = helper(answer);
    }
    return answer;
    }

    public int helper(int d){
    int val = 0;
    while(d!=0){
    val += d%10;
    d = d/10;
    }
    return val;
    }

    Also i feel that in your first approach we should convert number to string. These type of conversion are dangerous and leads to unpredictable results sometime.

  • Ahab Schmidt

    can you explain how to derive the 2nd solution? it’s not obvious at all.