Skip to problem
←

Reverse Integer

Easy 0 attempts

Given a signed 32-bit integer x, reverse its decimal digits while preserving its sign. Return the reversed integer if it lies within [-2147483648, 2147483647]; otherwise return 0.

Leading zeros in the reversed representation disappear: 120 becomes 21, and -120 becomes -21. Reversing 0 returns 0. The minus sign is not a digit and stays at the front.

For x = 1534236469, reversal would produce 9646324351, which exceeds the allowed range, so return 0.

Function contract

Implement reverse(x).

Output: Return the decimal digit reversal with its original sign, or 0 if it falls outside [-2147483648, 2147483647].

Example 1

Input
x = 123
Output
321

Example 2

Input
x = -123
Output
-321

Example 3

Input
x = 120
Output
21
Constraints
  • -2^31 <= x <= 2^31 - 1
Topics

Pop and Push Digits

Take the final digit with x % 10 and append it to the answer using result * 10 + digit. Remove that digit from x with Math.trunc(x / 10) and repeat until no digits remain.

JavaScript's remainder keeps the sign of the dividend, so negative inputs build a negative result directly. Truncation toward zero is essential: Math.floor would handle negative values incorrectly.

Finally check the signed 32-bit limits. A 32-bit input has at most ten decimal digits, so its full reversal remains exactly representable by JavaScript's Number type before this range check. Trailing input zeros contribute nothing before the first nonzero reversed digit.

javascript
function reverse(x) {
  let result = 0;
  while (x !== 0) {
    result = result * 10 + (x % 10);
    x = Math.trunc(x / 10);
  }
  return result > 2 ** 31 - 1 || result < -(2 ** 31) ? 0 : result;
}

Time: O(d), where d is the number of decimal digits | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript