Command Palette

Search for a command to run...

Lesson 39.3 · Math for Coding Interviews

Digits, Bases and Overflow

Extract digits with % 10 and / 10, convert between bases by repeated division, and check for overflow before it happens.

10 min

Think of it like this

Reading a car's odometer one wheel at a time from the right: the last digit is the remainder after dividing by 10, and dividing by 10 rolls the rest over.

1.Patterns

Digits: d = x % 10; x /= 10 (in Java, % keeps the sign of x, so −123 % 10 = −3).

Bases: Excel columns are base 26 with digits 1..26 (no zero): value = value × 26 + (c − 'A' + 1).

Overflow: before r = r * 10 + d, check r > (Integer.MAX_VALUE − d) / 10 (or use Math.multiplyExact, which throws). Counting factors often avoids big numbers entirely: trailing zeros of n! = n/5 + n/25 + n/125 + …

Remember

  • % 10 and / 10.
  • Check before you overflow.
  • Count factors instead of computing huge products.

Common mistakes

  • Computing n! to count its trailing zeros.