Start with 38. Add its digits and you get 11. Do it again and you get 2. That’s the whole problem: given a nonnegative integer, tell me which digit I’ll end up with.

A loop would do it. The interesting bit was the follow-up: could I get there in constant time, without a loop or a recursive call? Someone on LeetCode did it in one line:

1
2
def func(num):
return (num%9) or (9*bool(num))

It took me a minute to see what 9 had to do with anything. Write a four-digit number as 1000*a + 100*b + 10*c + d. If I subtract its digit sum, what’s left? 999*a + 99*b + 9*c. Every term is a multiple of 9. So the number I started with and the one I get after adding its digits have the same remainder on division by 9. That’s true on the next round, too.

Most of the time, the remainder is the final digit. When the remainder is zero, there are two possibilities. Start with 18 and you end up at 9; start with 0 and you stay at 0. That’s the job of 9*bool(num). Python’s or only gets to that part when the first answer is zero.

I love how much work that little or does.