Algorithm Puzzles: Add Digits

Algorithm Puzzles everyday every week sometimes: Add Digits

Puzzle

Puzzle from leetcode:

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Example 1:

1
2
3
4
5
6
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.

Solution

There is a math pattern in this puzzle:

1
2
3
4
5
6
7
class Solution {
public:
int addDigits(const int num) const {
int ret = num % 9;
return ret == 0 && num != 0 ? 9 : ret;
}
};

T.C.: O(1)
S.C.: O(1)