14. Reverse the Digits of a Number

Difficulty:EasyPattern:Digit ManipulationTime:O(d)Space:O(1)

Given an integer, reverse the order of its digits.

How It Works & Algorithmic Design

Build the reversed number from right to left:

  1. Extract the last digit using % 10.
  2. Shift the current result left by one decimal position using result * 10.
  3. Add the extracted digit.
  4. Remove the last digit from the original number using integer division by 10.
  5. 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: 1234
The digits need to be reversed.
Construction: 4 -> 43 -> 432 -> 4321
Each extracted digit is appended to the reversed number.
Output: 4321
The 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.