Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reverse a number in JavaScript
Our aim is to write a JavaScript function that takes in a number and returns its reversed number.
For example, reverse of 678 is:
876
There are multiple approaches to reverse a number in JavaScript. Let's explore the most common methods.
Method 1: Using String Conversion
The most straightforward approach converts the number to a string, reverses it, and converts back to a number:
const num = 124323;
const reverse = (num) => parseInt(String(num)
.split("")
.reverse()
.join(""), 10);
console.log(reverse(num));
323421
How It Works
Let's break down the string conversion method step by step:
- Let's say num = 123
- We convert the num to string ? num becomes '123'
- We split '123' ? it becomes ['1', '2', '3']
- We reverse the array ? it becomes ['3', '2', '1']
- We join the array to form a string ? it becomes '321'
- Finally we parse the string into an integer and return it ? 321
Method 2: Using Mathematical Approach
This method uses modulo and division operations without string conversion:
function reverseNumber(num) {
let reversed = 0;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num = Math.floor(num / 10);
}
return reversed;
}
console.log(reverseNumber(12345));
console.log(reverseNumber(678));
54321 876
Method 3: Handling Negative Numbers
For a more robust solution that handles negative numbers:
function reverseWithSign(num) {
const isNegative = num
54321
-876
21
Comparison
| Method | Readability | Performance | Handles Negatives |
|---|---|---|---|
| String Conversion | High | Medium | With modification |
| Mathematical | Medium | High | Needs additional logic |
| With Sign Handling | High | Medium | Yes |
Conclusion
The string conversion method is the most readable and commonly used approach for reversing numbers in JavaScript. For performance-critical applications, consider the mathematical approach.
