Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Build confidence with an intuition-first walkthrough focused on math fundamentals.
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Example 1:
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.
Example 2:
Input: num = 0 Output: 0
Constraints:
0 <= num <= 231 - 1Follow up: Could you do it without any loop/recursion in O(1) runtime?
Problem summary: Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math
38
0
happy-number)sum-of-digits-in-the-minimum-number)sum-of-digits-of-string-after-convert)minimum-sum-of-four-digit-number-after-splitting-digits)calculate-digit-sum-of-a-string)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #258: Add Digits
class Solution {
public int addDigits(int num) {
return (num - 1) % 9 + 1;
}
}
// Accepted solution for LeetCode #258: Add Digits
func addDigits(num int) int {
if num == 0 {
return 0
}
return (num-1)%9 + 1
}
# Accepted solution for LeetCode #258: Add Digits
class Solution:
def addDigits(self, num: int) -> int:
return 0 if num == 0 else (num - 1) % 9 + 1
// Accepted solution for LeetCode #258: Add Digits
impl Solution {
pub fn add_digits(mut num: i32) -> i32 {
((num - 1) % 9) + 1
}
}
// Accepted solution for LeetCode #258: Add Digits
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #258: Add Digits
// class Solution {
// public int addDigits(int num) {
// return (num - 1) % 9 + 1;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Simulate the process step by step — multiply n times, check each number up to n, or iterate through all possibilities. Each step is O(1), but doing it n times gives O(n). No extra space needed since we just track running state.
Math problems often have a closed-form or O(log n) solution hidden behind an O(n) simulation. Modular arithmetic, fast exponentiation (repeated squaring), GCD (Euclidean algorithm), and number theory properties can dramatically reduce complexity.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.