246. Digits Backwards

A retro scoreboard displays the digits of a number in the opposite order. Given the 32-bit signed integer x, return the integer formed by writing its decimal digits in reverse order, keeping the original sign.

Leading zeros that appear after reversing are simply dropped (1200 becomes 21), and 0 stays 0. If the reversed value lies outside the signed 32-bit range [-2147483648, 2147483647], return 0 instead.

For instance, 90210 becomes 1209, and -450 becomes -54. Because the reversed number can need more than 32 bits, such as 9999999991 for the input 1999999999, you must detect overflow without relying on a wider result being stored in the declared int type: either use a 64-bit intermediate or test the range before every digit is appended. Do not convert the number to a string. The intended solution runs in O(log x) time (number of digits) and O(1) space.

Example 1

Input:
x = 7508
Output:
8057
Explanation:

Reading 7508 from right to left gives 8057, which fits in 32 bits.

Example 2

Input:
x = -3070
Output:
-703
Explanation:

The sign is kept and the trailing zero disappears, so -3070 becomes -703.

Example 3

Input:
x = 1999999999
Output:
0
Explanation:

Reversed it would be 9999999991, which is above 2^31 - 1, so the answer is 0.

Constraints

-231 ≤ x ≤ 231 - 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(log x)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…