Extracting digits with % and /

Open on YouTube

1 A number has no index

Some problems give us a number and ask about its digits: how many there are, what they add up to, or whether the number reads the same backwards.

With an array, we would read nums[0], nums[1] and so on. A number has no positions to read. It is one value.

Two operators fix this, % and /. With them, we can take a number apart one digit at a time, using only whole numbers.

2 Two operators: % 10 and / 10

We write numbers in base 10. Every place is worth ten times the place to its right, so 4725 is 472 tens plus 5.

That gives us both operators:

  • n % 10 is the last digit. It is the remainder after dividing by 10. 4725 % 10 is 5.
  • n / 10 drops the last digit. Whole-number division throws the fraction away. 4725 / 10 is 472.
41000s7100s210s51sn % 10
n = 4725: % 10 reads the 5
4100s710s21s
n / 10 = 472: the 5 is gone

After / 10, the 2 is now the last digit, so % 10 reads it next. Python writes the division as n // 10, and JavaScript as Math.floor(n / 10).

3 Taking every digit in turn

We repeat the two steps until nothing is left. Each time round, we read the last digit, use it, and drop it. When n reaches 0, every digit has been used.

Here we add up the digits of 4725:

ndigit = n % 10totaln / 10
472555472
4722747
477144
44180

The digits come out from right to left: 5, 2, 7, 4. For a sum, the order does not matter. The loop stops at 0 and returns 18.

n is a 64-bit integer because the problems after this lesson give inputs up to about 9 × 10¹⁵. This code expects n ≥ 0. Section 6 deals with 0 and negative numbers.

4 Building a number back: reversing

The loop can also build a new number. To reverse 4725 into 5274, we keep a second number, rev, that starts at 0. For each digit, we shift rev one place left and put the digit on its end:

rev = rev * 10 + digit
ndigitrevn / 10
472555472
47225247
4775274
4452740

The digits leave the right end of n and join the right end of rev. So the first digit out ends up first in rev.

410s71s
n = 47: the 7 leaves the end
5100s210s71s
rev = 52 × 10 + 7 = 527

The original n is 0 by the end. If we still need it, for example to compare it with rev, we copy it before the loop.

5 Reversing can overflow

A sum of digits stays small. A reversed number does not. It has as many digits as the original, and a big digit can move to the front.

The number 1,000,000,009 fits in a 32-bit int, whose limit is a little over 2 × 10⁹. Its reverse is 9,000,000,001, which does not fit.

If rev is an int, the value wraps round without any error. Java prints 410,065,409, and the submission gets Wrong Answer.

So rev needs a type with room for the reversed value. With inputs up to about 9 × 10¹⁵, the reverse has at most 16 digits, and a 64-bit integer holds 18 digits easily.

6 Zero, negatives and trailing zeros

The loop above is right for most numbers. Three kinds of input break it:

  • n = 0. The check n > 0 fails at once, so the loop never runs. A digit count comes out as 0, but 0 has one digit. We handle 0 on its own before the loop.
  • Negative n. n > 0 fails again, so −472 gives a sum of 0. Changing the check to n != 0 is worse: -472 % 10 is −2, so the digits come out negative. We take the absolute value first and work with that.
  • Trailing zeros. 120 reversed is 21, not 021. The zeros at the end of n become leading zeros of rev, and a number has no leading zeros. This matters when we compare a number with its reverse.

7 How many steps it takes

Each time round, the loop removes one digit. So it runs once per digit, not once per unit of n.

nDigitsLoop steps
711
472544
1,000,000,0091010
9 × 10¹⁵1616

The number of digits grows with log₁₀ n, so the loop is O(log n). Even the largest input takes 16 steps. A loop from 1 to n would take around 10¹⁵ steps and get TLE.

There is also a formula for the digit count: ⌊log₁₀ n⌋ + 1. It works with doubles, and doubles are close, not exact. For 999,999,999,999,999, which has 15 digits, log10 returns exactly 15.0 and the formula says 16. It also fails on 0, where log₁₀ is not defined. The loop has neither problem.

8 When to use it

We reach for this loop when the input is a single number and the question is about its digits.

  • One digit at a time. Counting digits, counting the odd ones, and finding the largest one all use the loop from section 3. Only the line that uses digit changes.
  • Digits in reverse. When a problem compares a number with its mirror image, rev = rev * 10 + digit builds the mirror.
  • Two passes. Some problems need the digit count before they can use the digits. We run the loop once to count, then again on a copy of n.

The next lesson takes numbers apart in a different way, by what divides them.

The habit to keep: before submitting, run the code on 0, on a negative number, and on a number that ends in 0. Most digit bugs show up on one of those three.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.