clueless coding // TODO: be smarter

LeetCode 258. Add Digits: C++ Solution



Problem Statement


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

Function Signature (C++):
  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


int addDigitsHelper(int num) {
    int sum = 0;
    while (num > 0) {
        int current = num % 10;
        sum += current;
        num /= 10;
    }
    return sum;
}

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