↓Skip to main content
  1. LeetCode/

LeetCode 258: Add Digits

·1 min· ·
LeetCode Easy Math Simulation Number-Theory
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-22

  • Submissions: Runtime Error ×2 → Accepted ×4

Approach
#

Simulate: keep summing digits until a single digit remains (Math Template 5). For the O(1) follow-up: a number and its digit sum agree modulo 9 (since 10 ≡ 1 (mod 9)), so the final digit is n mod 9, except that multiples of 9 give 9 rather than 0: 0 if n == 0 else 1 + (n - 1) % 9.

My Attempts
#

The first two used sum(list(str(num))), adding characters (TypeError), and attempt 1 also misnamed the parameter nums. Converting to int first passed; In 2025 I rewrote it in Python and in C++. Every time I simulated rather than using the formula.

Solution
#

class Solution:
    def addDigits(self, num: int) -> int:
        return 0 if num == 0 else 1 + (num - 1) % 9

Complexity
#

Time O(1), space O(1).

Mistakes to Avoid
#

  • sum(list(str(n))) adds characters; convert to int first.
  • The formula must handle 0 and multiples of 9.

Interview Explanation
#

Simulation sums digits repeatedly; in O(1), a number and its digit sum are congruent mod 9, so the answer is 1 + (n - 1) % 9, with 0 for n = 0.

Related

LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive
LeetCode 171: Excel Sheet Column Number
·1 min
LeetCode Easy Math String
LeetCode 171 note: scan left to right with res = res × 26 + letter value (A = 1)
LeetCode 202: Happy Number
·1 min
LeetCode Easy Hash-Table Math Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 202 note: repeatedly take the sum of squared digits, which reaches 1 or enters a cycle; detect it with a set of seen numbers or fast and slow pointers
LeetCode 168: Excel Sheet Column Title
·2 mins
LeetCode Easy Math String
LeetCode 168 note: Excel columns are base 26 without a zero digit; take (n - 1) % 26 as the letter, then n = (n - 1) // 26
LeetCode 69: Sqrt(x)
·1 min
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 note: find the largest mid with mid² <= x; when a closed-interval search ends, r is the answer