% for digits, even/odd and wrapping around
n % 10 is the last digit, n // 10 drops it. i % len wraps an index back to the start. Three everyday uses of one operator.
The idea
a % b is the remainder after dividing a by b. It's always between 0 and b − 1 (for positive b in Python), which makes it perfect for three jobs.
Digits: n % 10 gives the last digit and n // 10 removes it. Even/odd: n % 2. Wrap-around: (i + k) % n moves k steps around a circle of n positions and lands back inside the array.
Worked example
Sum of the digits of 472
- 472 % 10 = 2, then 472 // 10 = 47
- 47 % 10 = 7, then 47 // 10 = 4
- 4 % 10 = 4, then 0 → stop. Sum = 2 + 7 + 4 = 13.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
n = 472
Solution · Pythonline 2
def digit_sum(n):total = 0while n > 0:total += n % 10 # last digitn //= 10 # drop itreturn total def rotate(nums, k):n = len(nums)return [nums[(i - k) % n] for i in range(n)] # rotate right by kStep 1 of 8· line 2
n % 10 is the last digit; n // 10 drops it. Repeat until nothing is left.
O(number of digits) = O(log₁₀ n) for digit loops.
How to spot it
- Digits of a number (Happy Number, Number, Reverse Integer).
- Circular arrays, rotating, “the next player in a circle”.
Common mistakes
- In Java/C++, -7 % 3 is -1, not 2. Use ((a % n) + n) % n to stay non-negative.
- Rotating by k ≥ n: reduce with k % n first.
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
- Second-largest distinct elementIndexing and walking through an arrayPractise ✎
- Count how often each number appearsCounting with a hash mapPractise ✎
- Remove duplicate characters, keep the firstA set for “have I seen this?”Practise ✎
- Reverse the order of wordsBuilding a new string or array as the answerPractise ✎
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →