Reverse Integer
Medium · Bit Manipulation
You are given a signed 32-bit integer. Reverse the order of its decimal digits, keeping the sign, and return the result. If reversing causes the value to fall outside the signed 32-bit integer range (-2147483648 to 2147483647), return 0 instead.
Examples
Input: x = 123
Output: 321
Why: Reversing the digits of 123 gives 321, which fits in a 32-bit signed integer.
Input: x = -120
Output: -21
Why: The sign is kept, and the trailing zero disappears when the digits 1,2,0 are reversed to 0,2,1.
Input: x = 1534236469
Output: 0
Why: Reversing gives 9646324351, which overflows the 32-bit signed range, so the result is 0.
Constraints
-2^31 <= x <= 2^31 - 1
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Reverse Integer. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.