Android & iPhone apps are coming soon. Log in for a plan and reminders made for you →

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.

In code (Python)

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

O(number of digits) = O(log₁₀ n) for digit loops.

How to spot it

  • Digits of a number (Happy Number, Palindrome 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.

Where it comes up

Go further