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

4 thoughts on “LeetCode – Add Digits (Java)”

  1. public int addDigits(int num) {
    if (num 9) {
    int firstDigit = num/10;
    int secondDigit = num%10;
    num = firstDigit + secondDigit;
    }
    return num;
    }

  2. 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.

Leave a Comment