Peel digits in a loop
Earlier you learned two tools: the remainder after dividing by 10 reads the last digit, and whole-number division by 10 drops it. A loop can use them again and again to visit every digit.
Read the last digit, do something with it, drop it, and repeat. When all the digits are gone, the number has become 0, and that is your signal to stop. The digits come out from right to left, so the last one comes first.
while n > 0:
digit = n % 10
n = n // 10Keep the best so far
What can you do with each digit? One idea is to find the biggest. Keep a box called best, starting at 0. For each digit you peel off, ask: is this one bigger than the best so far? If it is, put it in the box.
By the end, the box holds the biggest digit. This idea of keeping the best so far is useful all through programming, for biggest, smallest, longest and many more.
best = 0
while n > 0:
digit = n % 10
if digit > best:
best = digit
n = n // 10- n
- 3927
- best
- 7
- digit
- 7
The last digit is 7. It's bigger than the best so far, which is 0, so best becomes 7.