ORIGINAL CODING QUESTION
Single-digit badge code
A learning app turns a nonnegative integer x into a single-digit badge code: while the number has two or more decimal digits, replace it with the sum of its digits. Return the final single digit. The code for 0 is 0.
Original exercise · easy. Editorial role relevance does not imply a company has asked this question.
Input and output
A single integer x. Print the badge code.
Constraints
0 ≤ x ≤ 1,000,000,000.
Example 1
Input
9875
Output
2
9+8+7+5 = 29, then 2+9 = 11, then 1+1 = 2.
Example 2
Input
7
Output
7
A single digit is already a badge code.
Explain your approach
Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?
Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.
Hint 1
Extract digits with x % 10 and x / 10 (integer division).
Hint 2
Repeat the digit sum until the value is below 10.
Hint 3
A neat shortcut: for positive x the answer is 1 + (x - 1) % 9, because a digit sum keeps the same remainder modulo 9.
Practice this question
Save your work privately, explain decisions and return to your revision queue.
Open practice workspaceBrowse the question library →