Click here to Skip to main content
13,196,126 members (48,122 online)
Click here to Skip to main content
Add your own
alternative version

Stats

12.8K views
4 bookmarked
Posted 26 Aug 2016

How to Reverse a Number using JavaScript

, 26 Aug 2016
Rate this:
Please Sign up or sign in to vote.
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.

<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:

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)

Share

About the Author

Awesome Dev
United States United States
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
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
mvpKornfeld Eliyahu Peter31-Aug-16 9:04 
QuestionWith decimals... Pin
Member 1219848029-Aug-16 15:37
memberMember 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171019.1 | Last Updated 26 Aug 2016
Article Copyright 2016 by Awesome Dev
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid