Skills101
← All coding problems

Sum of Digits Until One Digit

easyPlacement Coding+10 XPTime limit 2s

Add up the digits of n. If the result has more than one digit, add up its digits again. Repeat until a single digit is left. For 9875: 9+8+7+5 = 29 → 2+9 = 11 → 1+1 = 2.

Input:

  • line 1: q
  • next q lines: one integer n

Output: q lines — the single digit for each number.

Constraints: 1 ≤ q ≤ 10⁴, 0 ≤ n ≤ 10¹⁸.

Think about it: the loop works and is fast enough. There is also a one-line formula: for n > 0 the answer is 1 + (n − 1) % 9. Can you see why it is linked to divisibility by 9?

Sample input 1

3
9875
0
9

Sample output 1

2
0
9

Sample input 2

2
18
10

Sample output 2

9
1

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.