Ctrl K

Fold the Digits Down to One

Easy
You are given a non-negative integer n. While it has more than one digit, replace it with the sum of its digits. Return the single digit you end up with. Can you do it in O(1), with no loops or recursion?
Example 1
n=4975 → 7

4 + 9 + 7 + 5 = 25, then 2 + 5 = 7, a single digit.

Example 2
n=6 → 6

The number already has one digit, so there is nothing to add.

Example 3
n=99 → 9

9 + 9 = 18, then 1 + 8 = 9.

Constraints
  • 0 ≤ n ≤ 2³¹ − 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTop of a Digit Pyramid EasyPrime Factor Sum Descent MediumSum of Binary Strings EasyCounting Off by Threes and Fives EasyAdding Long Numbers in Strings Easy
loading Python…
Input
n=4975
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 40 tests on the server, hidden ones included.