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.
Reversing the digits is the easy part. x % 10 is the last digit of x, and x / 10 (rounded toward zero) drops it. Take digits off the end of x one at a time and append each to a new number r with r = r * 10 + d. The first digit off x ends up at the front of r, and trailing zeros of x vanish on their own: 0 * 10 + 0 is still 0. Turning the number into text, reversing it and parsing it back works too, but it faces the same question at the end.
Time O(log |x|)Space O(1)
The full walkthrough and code are part of Premium
4096
6904