DEV Community

loading...

Reversing an Integer Mathematically

jenshaw profile image Jenny Shaw ・5 min read

The Problem

This an algorithm problem I've encountered a couple of times called Reverse the Integer.

Write a program or function called reverseInteger 
to reverse the order of digits of a given integer.

Input: 12345
Output: 54321

At first glance, it appeared easy enough to figure out. One of the first problems I ever remember having to solve was Reverse the String, and so, because the two seemed similar enough, I figured I could use the same approach for both.


Reverse the String

Here's one solution to Reverse the String:

function reverseString(str) {
  let reversedStr = '';  // initialize variable with empty string

  for (let i = str.length - 1; i >= 0; i--) {  // iterate backwards through each character of str (input)
    reversedStr = reversedStr.concat(str[i]);  // add each character to end of reversedStr
  }

  return reversedStr;  // after completion of iterations, return reversedStr
}

reverseString('dog')
// returns 'god' 

Here, I plan to return a variable called reversedStr at the end of my function. First, I initialize it as an empty string, and as I iterate backwards through each character of str, the original string input, I take that character to build up reversedStr using concatenation. Almost like .pop() and .push() in an array situation.


Reverse the Integer (like a string)

We could reverse integers using a similar algorithm, but there are a couple of caveats:

  • integers can't be iterated through, and
  • digits can't be concatenated.

If our input for reverseTheString() were an integer, the function would just spit back an empty string. Useless.

To resolve this, we'd have to first convert the integer input into a string before iteration and concatenation. And if we're expected to return an integer in the end, we'd also have to convert the string back into an integer before returning the value.

function reverseInteger(num) {
  let numStr = num.toString();  // <-- convert integer to string
  let reversedNumStr = '';

  for (let i = numStr.length - 1; i >= 0; i--) {
    reversedNumStr = reversedNumStr.concat(numStr[i]);
  }

  let reversedInt = Number(reversedNumStr); // <-- convert string back to integer
  return reversedInt; // return a reversed integer
}

reverseInteger(12345)
// returns 54321

I've never been very enthusiastic about reversing an integer like a string for a few reasons.

Although this function certainly gets the job done for (most) integer inputs, I don't like having to go through the extra trouble of converting data types back and forth. I'd rather stick to just one data type.

Also, we're asked to reverse integers, yet we're largely manipulating strings, so this feels like a rather tangential approach, a little like a cheat. And I'm no cheater, so we're going to learn to do this right.


Reverse the Integer with Math

Let's approach this problem instead in a way where we can still cleanly 'pop' and 'push' digits, do it all mathematically, and completely avoid the need to convert our integer into a string and back.

(By the way, if you're worried about the math, don't be. We're sticking with basic arithmetic here. Elementary school level stuff. If you understand subtraction, multiplication, division, and place values, then you've got this, kid.)

Keep in mind that in this function, we'll be handling two variables. The first, num, is the input from which we'll be 'popping' digits until there are none left. The second, reversedInteger, will be our output. Here we'll be building up the reversed order of digits by 'pushing' on the 'popped' digits from num.


Step 1:

We'll start with the variable, reversedInteger, and initialize its value at 0.

function reverseIntegerWithMath(num) {
  let reversedInteger = 0; // <-- initialize reversedInteger

}

Step 2:

We're going to start a while loop and continue it while num still has a value greater than 0. Every loop, we'll be chipping away one digit from num and using the digit to build reversedInteger.

function reverseIntegerWithMath(num) {
  let reversedInteger = 0;

  while (num > 0) { // <-- open while loop



  }
}

Step 3:

At the beginning of each loop, we'll multiply reversedInteger by 10.

function reverseIntegerWithMath(num) {
  let reversedInteger = 0;

  while (num > 0) {
    reversedInteger *= 10; // <-- set up for proper place value


  }
}

// Let's keep track of what num and reversedNumber look like 
// starting from here...

// num => 1234

// reversedInteger => 0 * 10 
//                 => 0

Step 4:

Now, let's take our num and divide by 10 using the modulo operator. This is to find a single-digit remainder which equals the current last digit of nums. We'll initialize a variable called rem at the top of our function, and tuck that value safely into it.

Then subtract rem from num and divide the result by 10. And now we're left with the same integer, but one digit less.

POP!

function reverseIntegerWithMath(num) {
  let reversedInteger = 0;
  let rem = 0;               // <-- initialize remainder

  while (num > 0) {
    reversedInteger *= 10;
    rem = num % 10;          // <-- remainder grabs last digit
    num = (num - rem) / 10;  // <-- eliminate zero in num
  }
}

// rem => 1234 % 10 
//     => 4

// num => 1234 - rem 
//     => 1230 / 10
//     => 123

// reversedInteger => 0

In case you're curious...
Why are we dividing and multiplying numbers by 10?

It's because we're replicating decimal place values where each place has a value of times ten from right to left.
Dividing by 10 eliminates the last zero in num, which then gives us access to the next digit that ends up in the ones place.
Multiplying reversedInteger by 10 makes room in the ones place where we can place the digit we popped off from num.


Step 5:

Next, it's time to "push" the "popped" digit from num by taking the remainder and adding it to reversedInteger.

PUSH!

function reverseIntegerWithMath(num) {
  let reversedInteger = 0;
  let rem = 0;

  while (num > 0) {
    reversedInteger *= 10;
    rem = num % 10;
    num = (num - rem) / 10;

    reversedInteger += rem;  // <-- 'push' remainder onto end of reversedInteger
  }
}

// rem => 4

// num => 123

// reversedInteger => 0 + 4
//                 => 4

Step 6:

We've completed one cycle of this process. Repeat until num's value dwindles to 0 and there are no more digits to 'pop' or 'push'.
After the reversal of digits is complete, we can finally return reversedInteger.

function reverseIntegerWithMath(num) {
  let reversedInteger = 0;
  let rem = 0;

  while (num > 0) {
    reversedInteger *= 10;
    rem = num % 10;
    num = (num - rem) / 10;

    reversedInteger += rem;
  }

  return reversedInteger;  // <-- done!
}

// if you want to see what happens in the next loop
// num => 123 - 3 (step 4)
//     => 120 / 10
//     => 12 [pops the 3 from original integer]

// rem => 123 % 10 (step 3)
//     => 3

// reversedInteger => 4 * 10 (step 2)
//                 => 40 + 3 (step 5)
//                 => 43 [pushes the 3 onto reversedInteger]


This is a pretty simple and neat trick in numeric manipulation and a much-improved approach to the reverseInteger problem. I'm always looking for other creative ways to solve simple problems like this, so if you've got clever ones to share, drop them in the comments!

Discussion

pic
Editor guide
Collapse
geluso profile image
Steve Geluso

Yessss! This is definitely a problem people should be exposed to. It's too common that people sneak out a solution via Strings. Excellent explanation!

Collapse
agurex profile image
Augusto Hernández

underrated!