Back to Interview Prep

Warm Up · Reverse Integer

Reverse Digits of an Integer

Problem Statement

Write a function reverse(x) that takes a 32-bit signed integer and returns its digits reversed. If the reversed value overflows the 32-bit signed integer range, return 0.

Requirements

  • Reverse the digits of a 32-bit signed integer.
  • Return 0 if the result overflows.

Examples

Input: 123→Output: 321

Input: -123→Output: -321

Input: 1534236469→Output: 0 (overflow)

Approach

  • Preserve the Original: Save x in xCopy.
  • Work with Absolute Value: Use Math.abs(x) or abs(x) to simplify reversal.
  • Reverse Digits: Initialize rev = 0. While x != 0: last = x % 10, rev = rev * 10 + last, x //= 10.
  • Check for Overflow: Return 0 if the reversed number is outside the 32-bit int range.
  • Restore Sign: Return -rev if xCopy < 0, else rev.

Time & Space Complexity

Time Complexity: O(d) - where d is the number of digits.

Space Complexity: O(1) - constant space.

Visualisation

1Start with the numberx = 123
2Take the last digit, push it onto revrev = 3 → 32 → 321
3Check the 32-bit limitrev > 2**31 - 1 → 0
4Restore the sign321

Your solution

Solve it in JavaScript and print the answer with console.log(). Run to see your output, then Submit to check it against the test cases.

// Write your solution in JavaScript
// Print the answer with console.log()


Console

No output yet. Use console.log() to print values here.

Write your own solution and press Submit once to unlock the answer.

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in