Skip to content
thesarfo

Reference

Extracting Digits

Printing the individual digits of a number using the modulo and divide-by-10 trick.

views 0

Given an input number, say 7789, print out the individual digits.

When we run 7789 % 10, we get 9 (the last digit). Why? Because numbers divisible by 10 (10, 20, 30, 40…) all end in zero, and a modulo simply divides and returns the remainder — the closest number that divides 10 evenly into 7789 is 7780, and the remainder is 9.

Now, to get the second-to-last digit 8: divide 7789/10, which gives 778.9 — we only care about the integer part, 778. Divide that by 10 again and take the remainder (778 % 10 = 8). To get 7: divide 778/10 = 77.8, then 77 % 10 = 7.

We repeat this “divide and modulo” logic until dividing our input number by 10 gives us zero. By that point we’ve extracted all the digits.

static void printDigits(int n){
while (n > 0){
int lastDigit = n % 10; // gives us the last digit - remainder
n = n / 10; // updates our input number to remove the last digit.
}
}