Given a signed 32-bit integer x, return the number you get by writing its digits in reverse order, keeping its sign. Zeros that end up at the front of the reversed number simply disappear, so 500 becomes 5.
The answer must also fit in a signed 32-bit integer, the range [-2³¹, 2³¹ - 1], which is [-2147483648, 2147483647]. If the reversed number falls outside that range, return 0 instead.
For an extra challenge, solve it without ever storing a value wider than 32 bits: notice the overflow before it happens rather than after.
Example 1
Input: x = 4096
Output: 6904
Example 2
Input: x = -870
Output: -78
The sign stays in front, and the trailing 0 of 870 becomes a leading zero, which is dropped.
Example 3
Input: x = 1999999999
Output: 0
Reversed, this is 9999999991, far above 2147483647, so the answer is 0.
Constraints
-2³¹ <= x <= 2³¹ - 1x % 10 gives the last digit and x / 10 drops it. Take digits off x one at a time and add each to the end of a new number with r = r * 10 + digit.
4096
6904