BeginnerMath for DSAArrays & Strings

% 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

  1. 472 % 10 = 2, then 472 // 10 = 47
  2. 47 % 10 = 7, then 47 // 10 = 4
  3. 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.

digit sum:
total ← 0
while n > 0:
total ← total + (n % 10)(the last digit)
n ← n // 10(drop it)
return total
even? x % 2 = 0
wrap around index ← (i − k) % n

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

n = 472

n = 472total = 0

Solution · Pythonline 2

def digit_sum(n):
total = 0
while n > 0:
total += n % 10 # last digit
n //= 10 # drop it
return total
def rotate(nums, k):
n = len(nums)
return [nums[(i - k) % n] for i in range(n)] # rotate right by k

Step 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

Where it comes up

Go further