Math Number tricks
91. Reverse Integer
You are given a signed 32-bit integer x. Return the number you get by writing the digits of x in reverse
order. The sign stays as it is, and zeros that end up at the front are dropped, so 1200 becomes 21 and −35
becomes −53.
A signed 32-bit integer holds the values from −231 to 231 − 1, that is from −2,147,483,648 to 2,147,483,647. If the reversed number is outside that range, return 0.
Interviewers ask for this problem to be solved with 32-bit integers only, as if no wider type existed. So no value in your code should go outside that range, even for a moment.
Example 1
Input: x = 1999999999
0Explanation: The digits reversed give 9,999,999,991. That is larger than 2,147,483,647, so the answer is 0.
Example 2
Input: x = -473
-374Explanation: The sign stays, and the digits 473 reversed are 374.
Example 3
Input: x = 8150
518Explanation: The digits reversed are 0518. The zero at the front is dropped, so the answer is 518.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
-231 ≤ x ≤ 231 − 1
Clarifying questions
What you would ask an interviewer before writing any code.