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-bitsigned integer. - Return
0if the result overflows.
Examples
Input: 123→Output: 321
Input: -123→Output: -321
Input: 1534236469→Output: 0 (overflow)
Approach
- Preserve the Original: Save
xinxCopy. - Work with Absolute Value: Use
Math.abs(x)orabs(x)to simplify reversal. - Reverse Digits: Initialize
rev = 0. Whilex != 0:last = x % 10,rev = rev * 10 + last,x //= 10. - Check for Overflow: Return
0if the reversed number is outside the32-bitint range. - Restore Sign: Return
-revifxCopy < 0, elserev.
Time & Space Complexity
Time Complexity: O(d) - where d is the number of digits.
Space Complexity: O(1) - constant space.
Visualisation
1Start with the number
x = 1232Take the last digit, push it onto rev
rev = 3 → 32 → 3213Check the 32-bit limit
rev > 2**31 - 1 → 04Restore the sign
321Your 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.