clueless coding // TODO: be smarter

LeetCode Add Digits: Java Solution



Problem Statement


Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Function Signature (Java):
  int addDigits(int num)

Inputs:
  num = 38

Outputs:
  2

Running 38 through addDigits would give something like this:
38 => 3 + 8
11 => 1 + 2
2



TL;DR Code Solution



public int getNext(int num) {
    int res = 0;
    while (num > 0) {
        res += num % 10;
        num /= 10;
    }
    return res;
}

public int addDigits(int num) {
    while (num > 9) {
        num = getNext(num);
    }
    return num;
}