How to reverse a number mathematically.

ManBearPig
3 min readNov 1, 2016

Jackson Bates recently published an article describing how mathematical solutions can be thousands of times more efficient than their iterative or recursive counterparts.

A useful exercise to help you start thinking about programming mathematically is to reverse an integer.

For those of you who like to cut to the chase and dive right into the code, here is a gist containing our algorithm.

For the rest of us who prefer to receive an explanation, let’s examine our 3-step method implemented in Python.

We will remove the last digit from our number and append it to the end of our reversed number variable until our original number is gone and the reversed number is complete.

Assuming that we have provided our algorithm an integer to work with,

Where number is a variable that originally contains our integer,

Where lastDigit is a variable that contains the last digit of number,

Where reverse is a variable representing the reverse of number.

Step 1 — Isolate the last digit in number

lastDigit = number % 10

The modulo operator (%) returns the remainder of a divison. In this case, we divide number by 10 and return the remainder. Consider the integer 1234. The tens column (30) is divided by 10 without remainder, the hundreds column (200) as well, and also the thousands column (1000). The remainder of the division will be 4 representing the ones column which could not be divided by 10. We now have the means to isolate the last digit of any integer. We save this in the variable lastDigit.

Step 2 — Append lastDigit to reverse

reverse = (reverse * 10) + lastDigit

We can start building the reversed number now by appending lastDigit onto the end of reverse. Remember that both of these variables are integers so we can not simply concatenate. We multiply reverse by 10 so that the ones column becomes the tens column, the tens column becomes the hundreds column, and so on. This also leaves us with a new ones column where we can add our lastDigit which we determined was 4 in our example.

reverse = (0 * 10) + 4

reverse = 4

We have successfully copied the last digit of number and appended it to reverse.

Step 3-Remove last digit from number

number = number / 10

Notice that number is still 1234, even though we have already used that 4 on the end. To remove the last digit from number we simply divide it by 10. This works because we are performing integer division which rounds results down to the nearest integer (ex. 244 / 10 = 24).

Iterate this process

while (number > 0)

Repeat this process until number is reduced to zero and reverse is completed.

Conclusion

This mathematical solution saved us from traversing arrays or other such methods which would have been less efficient.

--

--