14. Reverse the Digits of a Number
Given an integer, reverse the order of its digits.
How It Works & Algorithmic Design
Build the reversed number from right to left:
- Extract the last digit using
% 10. - Shift the current result left by one decimal position using
result * 10. - Add the extracted digit.
- Remove the last digit from the original number using integer division by
10. - Continue until the original number becomes
0.
Why This Approach Works Best
The algorithm processes each digit exactly once, requiring $O(d)$ time and $O(1)$ auxiliary space.
Example Walkthrough
Input:
1234The digits need to be reversed.
Construction:
4 -> 43 -> 432 -> 4321Each extracted digit is appended to the reversed number.
Output:
4321The digits appear in reverse order.
Answer: Reverse a number
function reverseNumber(n) {
const sign = n < 0 ? -1 : 1;
n = Math.abs(n);
let result = 0;
while (n > 0) {
const digit = n % 10;
result = result * 10 + digit;
n = Math.floor(n / 10);
}
return sign * result;
}💡 Extract digits from right to left and append them to a new number.
Key Takeaways
- Modulo extracts the final digit.
- Multiplying the result by 10 shifts existing digits left.
- The solution processes every digit once.