DEV Community

Alec DuBois
Alec DuBois

Posted on

Algorithm Toolkit #1: Modulo

Welcome to the part of this blog where I write about things I either:

A) Wish I had known when I started programming
B) Am really grateful someone taught me when I started programming

Oh, who am I kidding? That's my entire blog.

Let's talk about number manipulation for algorithms. More specifically, let's talk about the modulo, or remainder operator. (Quick note here: these are different things, but not for the purposes of the use case described in this post)

MDN says it best:

The remainder operator (%) returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.

So, 4 % 2 is 0, and 5 % 2 is 1.

Okay, we'll come back to that in a moment.

Let's say you're given a common algorithm: reverse digits.

The problem states that, given any integer as an argument, write an algorithm that returns the reverse of the digits of that integer. As an example, this algorithm, given 123, would return 321.

In JavaScript, you could achieve this using built-in methods:

  1. Turn the number into a string
  2. Turn the string into an array
  3. Reverse the array with .reverse()
  4. Turn the array back into a string
  5. Turn that string back into a number

But this defeats the point of algorithms: the point here is to use a lightsaber, not a blaster: a civilized weapon for a more civilized age.

So! Let's avoid all of this data manipulation entirely and leave the number as a number.

To reverse the number, we need to be able to extract a single digit from the number at a time.

It turns out that, given x being any integer, x % 10 always returns the last digit of that number. To continue the exmaple, 123 % 10 returns 3. There's our last digit!

If you wanted to simulate "popping" the digit off the number, you could, for example:

Disclaimer: this code assumes a positive number

let x = 123;

while (x > 0) {
  // Here's our x % 10 operator, storing the last digit in r
  const r = x % 10;

  x = (x - r) / 10; // This is the important part

  // Use the remainder for something here
}
Enter fullscreen mode Exit fullscreen mode

Pretty easy, right? Given that the remainder of x % 10 is the last digit of that number, you can then just subtract that remainder from the original number and divide by 10.

Given 123, one iteration would leave 12, then 1, and finally 1 - 1 / 10 is 0, which ends the loop.

You can use this any time you need to manipulate a number without converting it into a string! Try it out the next time you need to manipulate a number directly.

Discussion (0)