Given a non-negative integer num, repeatedly add all its digits until the result has only one digit, and return that digit.
Follow up: Can you do it without any loop or recursion, in O(1) time?
We use analytics and advertising cookies to understand how the site is used and whether our ads on Facebook and Instagram work. They are set only if you accept. See our Privacy Policy for details.
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit, and return that digit.
Follow up: Can you do it without any loop or recursion, in O(1) time?
An easy math problem, graded against 7 test cases (4 of them hidden).
Number theory, digit manipulation, and closed-form reasoning.
Reach for it when you see: Primes, digits, base conversion, or a problem with a formula hiding behind it.
More Math problems →Summing decimal digits preserves the value mod 9 (since 10 ≡ 1 mod 9), so repeating it converges to the number's residue class. The closed form is `0` for `num = 0` and `1 + (num - 1) % 9` otherwise - the `-1/+1` shift maps multiples of 9 to 9 instead of 0.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.