How to reverse a number in JavaScript
In this post, you will learn how to reverse a number in JavaScript. Such a type of question can improve your logical problem solving skills. The interviewer can ask you to reverse a number in JavaScript with some particular approach. Here, we have mentioned how to reverse a number in JavaScript using different approaches.
In-built methods to reverse a number
Here, we have used the function toString(), split(), reverse(), and join() methods to reverse a number. The toString() converts a given number into a string. The split() method divides a string into an ordered list of substrings, places them in an array, and returns the array. The reverse() method changes the sequence of elements of the given array and returns the reverse sequence, and the join() method returns the array as a string. The Math.sign(num) multiplies the number with the sign of the original number provided, and the parseFloat(num) converts num into a float from a string.
// program to reverse a number
function reversedNumber(num) {
return (
parseFloat(
num
.toString()
.split('')
.reverse()
.join('')
) * Math.sign(num)
)
}
num = 34122332;
document.write("Original number: "+num+"<br/>");
result = reversedNumber(num);
document.write("Reverse number: "+result+"<br/>");
Output of the above code -
Original number: 34122332
Reverse number: 23322143
Reverse a number using while loop
Here, we are using a while loop to reverse a number. In this, we have passed the number to the reversedNumber() function and created a variable 'temp' and initialised it to 0. The while loop runs until the value of num is greater than 0. Inside the loop, we are getting the last number and adding it to temp as the last number. So that, we can get the reverse of the number.
// program to reverse a number
function reversedNumber(num)
{
var a,b,temp=0;
b=num;
while(num>0)
{
a=num%10;
num=parseInt(num/10);
temp=temp*10+a;
}
document.write("Reverse number: "+temp+"<br/>");
}
num = 34122332;
document.write("Original number: "+num+"<br/>");
reversedNumber(num);
Output of the above code-
Original number: 34122332
Reverse number: 23322143
Related Articles
How to reverse string in JavascriptJavaScript display PDF in the browser using Ajax call
Parsing JSON in Javascript
Javascript speech recognition example
Select/deselect all checkboxes using Javascript
Print specific part of a web page in javascript
Dynamically Add/Delete HTML Table Rows Using Javascript
jQuery Ajax serialize form data example
Image popup on page load using HTML and jQuery
Ajax live data search using jQuery PHP MySQL
jQuery loop over JSON result after AJAX Success
Simple star rating system using PHP, jQuery and Ajax
jquery image zoom on mouseover example
Bootstrap star rating input example
Bootstrap datepicker example
Submit a form data without page refresh