I'm trying to solve an exercie in leetcode.com which deals with signed 32bit integers
.
The task is:
Return the inverse of a signed 32bit integer and return 0 if it overflows the 32bit signed integer's range.
In Wikipedia:
A 32-bit register can store 32 different values. The range of integer values that can be stored in 32 bits depends on the integer representation used. With the two most common representations, the range is 0 through 4,294,967,295 (2^32 − 1) for representation as an (unsigned) binary number, and −2,147,483,648 (−2^31) through 2,147,483,647 (2^31 − 1) for representation as two's complement.
So, if what i understood is correct i should test between the intervals 0 to (2^31)-1
and (-2^31) to 0
otherwise, return 0
.
Here is my code:
def reverse_int(nums):
a = str(nums)
if 0 < nums <= (1 << 31)-1:
return int(a[::-1])
elif (-1 << 31) <= nums < 0:
return -(int(a[:-len(a):-1]))
else:
return 0
Here is my problem: When i test my code on the website with:
nums = 1534236469 # Fail
nums = 1463847412 # Success
nums = 9000000 # Success
Why my current code fails with 1534236469
? isn't 1534236469
in the range of 32 bit signed integers
? What i'm missing ?
1534236469
on the website it should return 0. This means that1534236469
overflows the range of 32 bit signed integers.the two most common representations
. There is other representations of 32bit integers ?