JavaScript Program to Reverse Number Using While Loop
num % 10, building the reversed number with reversed = reversed * 10 + digit, and reducing the original number with Math.floor(num / 10) until it becomes zero.Examples
How to Think About It
% to get the last digit, then add it to the reversed number after shifting the reversed number's digits left by multiplying by 10. Remove the last digit from the original number by dividing by 10 and taking the floor. Repeat until the original number is zero.Algorithm
Code
function reverseNumber(num) { let reversed = 0; while (num > 0) { let digit = num % 10; reversed = reversed * 10 + digit; num = Math.floor(num / 10); } return reversed; } console.log(reverseNumber(1234));
Dry Run
Let's trace reversing the number 1234 through the code
Start
num = 1234, reversed = 0
First loop iteration
digit = 1234 % 10 = 4; reversed = 0 * 10 + 4 = 4; num = Math.floor(1234 / 10) = 123
Second loop iteration
digit = 123 % 10 = 3; reversed = 4 * 10 + 3 = 43; num = Math.floor(123 / 10) = 12
Third loop iteration
digit = 12 % 10 = 2; reversed = 43 * 10 + 2 = 432; num = Math.floor(12 / 10) = 1
Fourth loop iteration
digit = 1 % 10 = 1; reversed = 432 * 10 + 1 = 4321; num = Math.floor(1 / 10) = 0
End
num is 0, loop ends, reversed = 4321
| num | digit | reversed |
|---|---|---|
| 1234 | 4 | 4 |
| 123 | 3 | 43 |
| 12 | 2 | 432 |
| 1 | 1 | 4321 |
Why This Works
Step 1: Extract last digit
Using num % 10 gets the last digit of the number, like peeling one digit off.
Step 2: Build reversed number
Multiply the current reversed number by 10 to shift digits left, then add the extracted digit to append it.
Step 3: Remove last digit
Divide the original number by 10 and use Math.floor to drop the last digit, preparing for the next loop.
Alternative Approaches
function reverseNumberString(num) { return Number(num.toString().split('').reverse().join('')); } console.log(reverseNumberString(1234));
function reverseNumberRecursive(num, reversed = 0) { if (num === 0) return reversed; return reverseNumberRecursive(Math.floor(num / 10), reversed * 10 + num % 10); } console.log(reverseNumberRecursive(1234));
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time grows linearly with the number of digits.
Space Complexity
Only a few variables are used, so space is constant regardless of input size.
Which Approach is Fastest?
The while loop method is efficient and uses constant space, while string conversion uses extra memory and recursion adds call stack overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| While loop | O(d) | O(1) | Efficient and memory-friendly |
| String conversion | O(d) | O(d) | Simple code, less efficient for large numbers |
| Recursive | O(d) | O(d) | Elegant but risks stack overflow |
Math.floor to safely remove the last digit when dividing by 10.Math.floor causes the number to become a decimal and breaks the loop.