Add Digits
Easy · Math & Geometry · Explanation and code example
Digital Root Modulo Nine
How it works
A number has the same remainder modulo nine as the sum of its decimal digits, because ten is congruent to one modulo nine. Repeating digit sums therefore yields its digital root: zero stays zero, and a positive multiple of nine maps to nine.
Steps
- Return zero for input zero.
- For positive input compute 1 + (num - 1) % 9.
- Return the single-digit result.
Complexity
- Time: O(1) for fixed-width input.
- Space: O(1).
Things to watch for
- A positive multiple of nine returns nine, rather than zero.
- Keep zero as its own case.
- The input is nonnegative.
Python code example
class Solution:
def addDigits(self, num: int) -> int:
return 0 if num == 0 else 1 + (num - 1) % 9
C++ code example
class Solution {
public:
int addDigits(int num) {
return 1 + (num - 1) % 9;
}
};
Source and license
Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.