All five problems on this page use the digit loop from 4.0.0. n % 10 reads the last digit. n // 10 removes it. Only what you do with each digit changes.
def digit_sum(n: int) -> int: n = abs(n) total = 0 while n > 0: total += n % 10 # add the last digit n //= 10 # drop the last digit return totalprint(digit_sum(4721)) # → 14
Zero needs no special case here. The loop does not run, and the sum stays 0, which is correct.
This one needs a moment of thought. We read digits from the right. We need to build a new number where each new digit goes on the right end.
How do you add a digit to the right end of a number? Multiply by 10, which shifts every digit one place left and leaves a 0 at the end. Then add the new digit into that empty place. Adding 4 to the end of 127 is 127 \times 10 + 4 = 1274.
python
def reverse_number(n: int) -> int: sign = -1 if n < 0 else 1 # (1) n = abs(n) rev = 0 while n > 0: rev = rev * 10 + n % 10 # (2) n //= 10 # (3) return sign * revprint(reverse_number(4721)) # → 1274print(reverse_number(-120)) # → -21
(1) Remember the sign and work on the positive number. Put the sign back at the end.
(2) Shift rev left by one place and drop the last digit of n into the gap.
(3) Remove that digit from n.
Trace on 4721:
n before
last digit
rev after
4721
1
0 \times 10 + 1 = 1
472
2
1 \times 10 + 2 = 12
47
7
12 \times 10 + 7 = 127
4
4
127 \times 10 + 4 = 1274
Trailing zeros vanish.-120 reverses to -21, not -021. A number cannot start with zero, so the leading 0 of the reverse simply disappears. If the interviewer wants the zero kept, the answer must be a string.
In other languages this can overflow. Reversing 1,999,999,999 gives 9,999,999,991, which does not fit in a 32-bit integer. LeetCode's "Reverse Integer" asks you to return 0 in that case. 4.30.7 solves that version.
A palindrome reads the same forwards and backwards. The word comes from Greek, meaning "running back again".
The simple answer: reverse the number and compare.
python
def is_palindrome_number(n: int) -> bool: if n < 0: return False # (1) return n == reverse_number(n)print(is_palindrome_number(12321)) # → Trueprint(is_palindrome_number(-121)) # → Falseprint(is_palindrome_number(10)) # → False
(1) A negative number cannot be a palindrome. -121 backwards is 121-, and the minus sign is now at the wrong end.
The half-reverse trick. You only need to reverse half the number. Keep moving digits from n into rev until rev is at least as big as what is left of n. Then you have reached the middle.
python
def is_palindrome_half(n: int) -> bool: if n < 0 or (n % 10 == 0 and n != 0): # (1) return False rev = 0 while n > rev: # (2) rev = rev * 10 + n % 10 n //= 10 return n == rev or n == rev // 10 # (3)print(is_palindrome_half(1221)) # → Trueprint(is_palindrome_half(12321)) # → Trueprint(is_palindrome_half(1230)) # → False
(1) A number ending in 0 would have to start with 0 to be a palindrome. Only 0 itself does that. Without this line, 10 would wrongly pass. The first step moves the 0 into rev, so rev stays 0 and n becomes 1. The second step moves the 1, so rev becomes 1 and n becomes 0. Now line (3) checks 0 == 1 // 10, which is 0 == 0, and says True. The leading zero of the reverse has vanished, which is exactly the problem.
(2) Stop when rev catches up with what is left of n.
(3) Even length: the two halves match exactly. For 1221, we stop at n = 12, rev = 12. Odd length: the middle digit ended up in rev, so drop it with // 10. For 12321, we stop at n = 12, rev = 123, and 123 // 10 is 12.
This version does half the work. It also matters in languages with fixed-size integers, because the full reverse of a large number can overflow, while half of it never can.
5. Digital root: add the digits until one is left
python
def digital_root_loop(n: int) -> int: while n >= 10: n = digit_sum(n) return nprint(digital_root_loop(4721)) # → 5
That works, but there is a well-known shortcut with no loop at all.
Why this works. The number 10 is 1 more than 9. So 10 \bmod 9 = 1, and 100 \bmod 9 = 1, and every power of 10 leaves remainder 1 when divided by 9. Now write 4721 = 4 \times 1000 + 7 \times 100 + 2 \times 10 + 1. Divide each part by 9. Each power of 10 acts like a 1. So 4721 leaves the same remainder as 4 + 7 + 2 + 1.
In plain words: a number and the sum of its digits leave the same remainder when divided by 9. Adding digits again and again never changes that remainder. So the final single digit is just the remainder after dividing by 9. There is one adjustment. When the remainder is 0 (for 9, 18, 27 and so on) the digital root is 9, not 0. The formula 1 + (n - 1) % 9 handles that. It shifts the range down by one, takes the remainder, then shifts back up, so the answers run from 1 to 9 instead of 0 to 8.
This fact is centuries old. Accountants used it as casting out nines to check sums by hand long before calculators. It is also why "a number is divisible by 9 exactly when its digit sum is divisible by 9".
The loops each run once per digit, which is O(\log n) time. The half-reverse runs half as many steps. The digital-root formula is O(1). All of them use O(1) memory.
These are the questions that usually come right after you solve it. Each one has a short, plain answer you can say out loud.
"Can you do it without turning the number into a string?" Yes. Use the digit loop. n % 10 gives the last digit, and n // 10 removes it. Repeat until n is 0.
"What about 0 and negative numbers?" 0 has one digit, so count-digits needs a special case for it. For negative numbers, work on abs(n) and put the sign back at the end. A negative number is never a palindrome, because the minus sign is only at the front.
"Can reversing a number overflow?" Not in Python. In Java or C it can. Reversing 1,999,999,999 gives 9,999,999,991, which is too big for a 32-bit integer. The half-reverse method avoids this, because half of a number is always small enough.
"Can you find the digital root without a loop?" Yes: 1 + (n - 1) % 9, with 0 giving 0. It works because a number and the sum of its digits always leave the same remainder when divided by 9.
One thing to volunteer: "The digit-sum rule for checking divisibility by 9 comes from the same fact as the digital-root formula."