Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / Javascript
Tip/Trick

How to Reverse a Number using JavaScript

Rate me:
Please Sign up or sign in to vote.
4.78/5 (4 votes)
26 Aug 2016CPOL2 min read 54.7K   4   6
Interview question: how do you reverse a number using JavaScript?

Introduction

I recently had an interview and was asked to create a JavaScript function that would reverse a number (i.e., given 123, the outcome is 321). This was quite simple to me, so I answered "convert the number to a string and reverse the digits". Unfortunately, this was not the answer they were looking for. They wanted a solution that did not use any strings or (string) conversion (they wanted me to invent the wheel).

Background

On the spot in an interview, I saw some beautiful symmetry in a solution for reversing a number. I knew right away this would involve the mod (%) operator and some looping.

Using the Code

This solution can be used in client side programming to reverse a number.

JavaScript
<script language='javascript'>
Reverse = function(number) {
 var reversed = 0;

 while (number != 0) {
  reversed *= 10;
  reversed += number % 10;
  number -= number % 10;
  number /= 10;
 }

 return reversed;
}
</script>

// Here's a simple way to test the function:

<body>
<input type='text' id='string'/>&nbsp;<input type='button' value='text' 
 onclick='alert("reversed = " + Reverse(document.getElementById("string").value);'/>
</body>

This little function has a simple loop that executes until the incoming parameter (number) becomes zero. Notice the symmetry between "number" and "reversed", inside the loop. The value of "reversed" (result) starts out at zero and keeps getting multiplied by 10 and then increased by the number mod 10. The "number" (incoming value) keeps getting decreased by the number mod 10 and then is divided by 10.

One member responded to our tip asked "what about reversing 12345.6789 into 9876.54321"? This becomes challenging (dealing with a decimal), given the assumption "thou shalt not manipulate the string"! Here is my solution:

JavaScript
Reverse = function(number) {
 var reversed = 0;  
 var exponent = number.indexOf('.');

 if (exponent !== -1) {
  number *= Math.pow(10, number.length - exponent - 1);
 }

 while (number != 0) {
   reversed *= 10;
   reversed += number % 10;
   number -= number % 10;
   number /= 10;
 }

 if (exponent !== -1) {
  reversed /= Math.pow(10, exponent);
 }

 return reversed;
}

This snippet shows how we can first: adjust the (floating point) number to make it an integer value, then follow the same loop process as in the preceding snippet, and last adjust the reversed result for the decimal. We use Math.pow() with base 10 and an exponent to accomplish this.

Points of Interest

I don't know why there would ever be a need to reverse a number but this was a fun problem to solve. Hope this article peaks your interest in client side programming and gets you thinking toward more elegant solutions!

History

This is the initial revision.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionreverse in single line JS code, try this Pin
aneeshchopra13-Jan-20 21:59
aneeshchopra13-Jan-20 21:59 
QuestionTRY THIS ONE TO REVERSE NUMBER IN JAVASCRIPT Pin
Member 1237643313-Nov-17 2:42
Member 1237643313-Nov-17 2:42 
SuggestionDo not use indexOf Pin
-=at=-13-Jan-17 2:52
professional-=at=-13-Jan-17 2:52 
SuggestionFar too complicated... Pin
Kornfeld Eliyahu Peter31-Aug-16 9:04
professionalKornfeld Eliyahu Peter31-Aug-16 9:04 
QuestionWith decimals... Pin
Member 1219848029-Aug-16 15:37
Member 1219848029-Aug-16 15:37 
QuestionSmart Pin
phil.o26-Aug-16 7:41
professionalphil.o26-Aug-16 7:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.