JavaScript Program to Reverse a Number with Output
Number(String(num).split('').reverse().join('')).Examples
How to Think About It
Algorithm
Code
function reverseNumber(num) { return Number(String(num).split('').reverse().join('')); } console.log(reverseNumber(12345));
Dry Run
Let's trace reversing the number 12345 through the code
Convert number to string
num = 12345 -> String(num) = '12345'
Split string into array
'12345' -> ['1', '2', '3', '4', '5']
Reverse the array
['1', '2', '3', '4', '5'] -> ['5', '4', '3', '2', '1']
Join array back to string
['5', '4', '3', '2', '1'] -> '54321'
Convert string to number
Number('54321') -> 54321
| Step | Value |
|---|---|
| String(num) | '12345' |
| Split | ['1','2','3','4','5'] |
| Reverse | ['5','4','3','2','1'] |
| Join | '54321' |
| Number | 54321 |
Why This Works
Step 1: Convert number to string
Using String(num) lets us treat the number like text so we can work with each digit.
Step 2: Reverse the digits
Splitting into an array and reversing it flips the order of digits easily.
Step 3: Convert back to number
Joining the reversed array and converting back to a number gives the reversed numeric value.
Alternative Approaches
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));
function reverseNumber(num, rev = 0) { if (num === 0) return rev; return reverseNumber(Math.floor(num / 10), rev * 10 + num % 10); } console.log(reverseNumber(12345));
Complexity: O(n) time, O(n) space
Time Complexity
The time depends on the number of digits n, as splitting, reversing, and joining each process all take O(n) time.
Space Complexity
Extra space is needed for the array of digits, so space complexity is O(n).
Which Approach is Fastest?
The math-based loop method uses O(1) space and can be faster for very large numbers, while string methods are simpler and more readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String methods | O(n) | O(n) | Simplicity and readability |
| Math and loops | O(n) | O(1) | Performance with large numbers |
| Recursion | O(n) | O(n) | Elegant code but limited by call stack |