Reverse a Number (JavaScript)

Reverse a Number

Reversing a number means taking its digits and arranging them in reverse order. For example, reversing 123 gives 321. This is a common logical programming problem that helps to practice arithmetic operations and loop control.

Understanding the Concept

The core idea involves extracting the last digit of the number, appending it to a reversed number, and then removing that last digit from the original number until the original number becomes zero. This process typically uses the modulo operator (%) to get the last digit and integer division (Math.floor()) to remove it.

Common Approaches

1. Using a while loop (Iterative Method):

This is the most common and explicit way to reverse a number digit by digit.

Copy to Clipboard

Explanation:

  • reversedNum is initialized to 0.
  • The while loop continues as long as originalNum is greater than 0.
  • lastDigit = originalNum % 10; extracts the rightmost digit.
  • reversedNum = reversedNum * 10 + lastDigit; builds the reversed number. Multiplying by 10 shifts existing digits to the left.
  • originalNum = Math.floor(originalNum / 10); removes the rightmost digit from originalNum.
  • Special handling for negative numbers: reverse the absolute value and then apply the negative sign back.
2. Converting to String and Reversing (Simplified Method):

This method leverages string manipulation functions available in JavaScript, often leading to more concise code, especially for positive integers.

Copy to Clipboard

Explanation:

  • The number is converted to its absolute value string representation.
  • split('') converts the string into an array of characters.
  • reverse() reverses the order of elements in the array.
  • join('') concatenates the array elements back into a string.
  • Finally, Number() converts the reversed string back to a number.
  • The original sign is reapplied.

Key Takeaways

  • Modulo and Division: Essential for digit-by-digit processing of numbers.
  • Type Conversion: Converting between numbers and strings can simplify certain problems.
  • Handling Edge Cases: Consider negative numbers and numbers ending in zero (e.g., reversing 120 should yield 21, not 021, which Number() handles correctly).
  • Efficiency: The iterative method (Method 1) is generally more efficient for very large numbers as it avoids string conversions, though for typical integer sizes, the string method is often clear enough.