Problem 258

Abstract / Summary

Repeatedly add the digits of a number until a single digit remains and return it.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
11 lines | 252 bytes | submitted August 12, 2023 | GitHub   11% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (1+ million submissions).

Typical patterns to solve this problem:
  • Math
  • Number Theory
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.69 | σ = 2.00

Complexity Analysis

Time: logarithmic
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
51 links | 37 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Add Digits | LeetCode 258 | C++, Java, Python3 | O(1)'
Knowledge Center 18 mins
Add Digits | LeetCode 258 | C++, Java, Python3 | O(1)
YouTube video 'Add Digits | Leet code 258 | Theory explained + Python code | July Leet code challenge'
Sai Anish Malla 9 mins
Add Digits | Leet code 258 | Theory explained + Python code | July Leet code challenge
YouTube video 'Add Digits| Leetcode 258| Live Coding session 🔥🔥🔥|  2 Approaches 💯💯 | String and Maths'
Coding Decoded 7 mins
Add Digits| Leetcode 258| Live Coding session 🔥🔥🔥| 2 Approaches 💯💯 | String and Maths
YouTube video '258. Add digits | Leetcode | Math based | Fundamentals'
Coding with Tamilarasan 7 mins
258. Add digits | Leetcode | Math based | Fundamentals
YouTube video 'Add Digits with O(1) runtime - LeetCode #258 - Python, JavaScript, Java, C++'
CodingNinja 10 mins
Add Digits with O(1) runtime - LeetCode #258 - Python, JavaScript, Java, C++
YouTube video 'Add Digits - Leetcode 258 - Python'
Algorithms Casts 8 mins
Add Digits - Leetcode 258 - Python
YouTube video 'Add Digits | Leetcode 258 | Brute Force, Recursion, Math | Python Telugu | srkcodes'
Srk Codes 13 mins
Add Digits | Leetcode 258 | Brute Force, Recursion, Math | Python Telugu | srkcodes
YouTube video '258 || Add Digits || C++ || Leetcode Daily Challenge'
CodeFreaks 5 mins
258 || Add Digits || C++ || Leetcode Daily Challenge
YouTube video 'Daily Leetcode #1121: Apr 26, 2023 - 258. Add Digits'
Programming Live with Larry 4 mins
Daily Leetcode #1121: Apr 26, 2023 - 258. Add Digits
YouTube video 'Daily Leetcode #679: Feb 08, 2022 - 258. Add Digits'
Programming Live with Larry 6 mins
Daily Leetcode #679: Feb 08, 2022 - 258. Add Digits
YouTube video 'Leetcode | 258. Add Digits | Easy | Javascript'
Software Interviews Prep 7 mins
Leetcode | 258. Add Digits | Easy | Javascript
YouTube video '258. Add Digits | JavaScript | O(1) TC | Two approaches explained | LeetCode Daily Challenge'
LeetCodeWithMonu 15 mins
258. Add Digits | JavaScript | O(1) TC | Two approaches explained | LeetCode Daily Challenge
YouTube video 'Add Digits - LeetCode 258  - Java Solution'
algobest - Computer Science 3 mins
Add Digits - LeetCode 258 - Java Solution
YouTube video 'Daily Leetcode #117: Jul 26, 2020 - 258. Add Digits'
Programming Live with Larry 5 mins
Daily Leetcode #117: Jul 26, 2020 - 258. Add Digits
YouTube video 'LeetCode 258 | Add digits | Easy | Efficient Solution Explained |'
Code Scribbler 5 mins
LeetCode 258 | Add digits | Easy | Efficient Solution Explained |
YouTube video 'Leetcode Problem 258 - Add Digits'
Tech By Ralph 7 mins
Leetcode Problem 258 - Add Digits
YouTube video 'Day 565: LeetCode Problem 258. Add Digits - Swift'
iOSxBank 4 mins
Day 565: LeetCode Problem 258. Add Digits - Swift
YouTube video 'Leetcode 258  Add Digits'
Math Geeks 5 mins
Leetcode 258 Add Digits
YouTube video 'Leetcode | Easy | 258. Add Digits | Mathematical: Digital Root | Time: O(1) | Javascript'
Software Interviews Prep 4 mins
Leetcode | Easy | 258. Add Digits | Mathematical: Digital Root | Time: O(1) | Javascript
YouTube video 'Add Digits | Leetcode 258 | Approach + Code with explanation.'
Pirai's Academy 7 mins
Add Digits | Leetcode 258 | Approach + Code with explanation.
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

7 similar problems

Solved On The Same Day

5 easy
6 solutions   August 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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