Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Use a while loop to find how many digits has and what the sum of its digits is.
n % 10 is the last digit and n // 10 removes it.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, compare your working with the solution.
Plan. In every round, take the last digit with n % 10 and remove it with n // 10. Repeat while n > 0.
| Round | last digit | n after |
|---|---|---|
| 1 | 9 | 472 |
| 2 | 2 | 47 |
| 3 | 7 | 4 |
| 4 | 4 | 0 |
The loop ends when n is 0.
Answer: digits, and the sum is .
Log in to join the discussion.
Loading…