C++ 0258.cpp
class Solution:
def addDigits(self, num: int) -> int:
if (num < 10):
return num
sum = 0
while num > 0:
sum = sum + num % 10
num = num // 10
return self.addDigits(sum)
Difficulty
and has an acceptance rate of about 69% (1+ million submissions).
Typical patterns to solve this problem:
- Math
- Number Theory
- Simulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single method addDigits. The method computes the repeated sum of the decimal digits of an integer until the result is a single-digit number. The algorithm follows a straightforward recursive approach: it first checks whether the input already satisfies the termination condition, then reduces the number by summing its digits, and finally recurses on the intermediate sum.
Key Steps
The first logical step is the termination test that determines whether the input number is already a single digit. This is expressed by a simple conditional check:
if (num < 10):
return num
When the condition holds, the method returns the input unchanged, handling the edge case where the original value is a single digit, including zero.
The second step initializes an accumulator that will hold the sum of the digits. The accumulator is set to zero before entering the digit-extraction loop:
sum = 0
The third step iteratively extracts each decimal digit from the number, adds it to the accumulator, and discards the processed digit. This loop continues until all digits have been consumed:
while num > 0:
sum = sum + num % 10
num = num // 10
Inside the loop, the expression num % 10 yields the least-significant digit, and num // 10 removes that digit from the number. The loop terminates when num becomes zero, guaranteeing that every digit has contributed to the accumulator.
The final step invokes the same method recursively on the computed digit sum, thereby repeating the process until a single-digit result emerges:
return self.addDigits(sum)
Because each recursive call receives a strictly smaller integer (the sum of its digits), the recursion inevitably reaches the base case defined in the first step.
Edge Cases Handled
The explicit base-case check (num < 10) ensures that inputs already consisting of a single digit are returned immediately without further processing. This includes the value zero, which is a valid single-digit input and is correctly returned. The loop condition while num > 0 naturally skips execution when the number is zero, preventing an unnecessary iteration and leaving the accumulator at its initial value of zero, which then satisfies the base case on the subsequent recursive call.
Performance Optimizations Observed
The algorithm reduces the problem size in two complementary ways. First, the digit-extraction loop processes each decimal digit exactly once, using integer arithmetic (% and //) that operates in constant time for typical machine word sizes. Second, the recursive call receives the sum of digits, which is guaranteed to be smaller than the original number and often dramatically smaller, especially for large inputs. This rapid contraction of the input magnitude limits the total number of recursive invocations. The use of a local accumulator variable avoids the overhead of creating additional data structures, keeping the memory footprint minimal throughout execution.
ELI5 - Simplified Explanation
Imagine you have a big pile of building blocks that represents a tall number, and you want to shrink it down until it is just a single digit sitting by itself. The computer looks at the number you give it, and if that number is already small like zero, one, or even nine, it stays exactly the same because it is already a single digit.
If the number is much bigger, the computer plays a game where it breaks the number apart into little pieces by looking at each digit one by one. It adds those pieces together to make a brand new, smaller number. Once it has that new, smaller sum, it checks it again to see if it is now just a single digit. If it is still too big, the computer starts the whole process over again with the new number until it finally reaches a single digit. It is like taking a big tower of blocks and breaking it down over and over until you only have one block standing.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | |||||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 202: Happy Number
- problem 1085: Sum of Digits in the Minimum Number
- problem 1945: Sum of Digits of String After Convert
- problem 2160: Minimum Sum of Four Digit Number After Splitting Digits
- problem 2243: Calculate Digit Sum of a String
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 2544: Alternating Digit Sum
Solved On The Same Day
- problem 231: Power of Two
- problem 232: Implement Queue using Stacks
- problem 268: Missing Number
- problem 326: Power of Three
- problem 338: Counting Bits
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality