Skip to content
CodeKruPro

Add the digits until one digit remains

Coding problemEasyAsked in: Zupee

Given a non-negative integer n, add up its digits. If the result has more than one digit, add up its digits again. Repeat until a single digit remains, and return it.

For 38: 3 + 8 = 11, then 1 + 1 = 2, so the answer is 2.

Examples

Example 1
Input: n = 38
Output: 2
Example 2
Input: n = 0
Output: 0
Example 3
Input: n = 9875
Output: 2
9 + 8 + 7 + 5 = 29, 2 + 9 = 11, 1 + 1 = 2.

Constraints

  • n is between 0 and 2,147,483,647

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in