Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2**31, 2**31 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
This is my submission
class Solution(object):
def reverse(self, x):
sp= str(abs(x))[::-1].lstrip("0")
ans= int(sp)
if x > 0 :
return ans
else:
return -1*ans
The int() method should allow me to pass a string value ("12"), but it returns an error saying that it's an invalid literal for int().
The variable sp in line 3 is a str not a float, so I have no idea why it doesn't run on the leetcode submission page, as it runs ok on VSCode.
Is there any grading guideline that I missed?
And, this is the Value Error I'm getting
There are two problems with the original code: (1) It won't handle zero, and (2) The range checks in the problem description are missing.
For zero, the string representation is "0"
. But after calling lstrip("0")
, it will be the empty string, which int
won't accept. This can be fixed by making a special-case check for zero. An even simpler fix (suggested by Mark) is not to strip the leading zeros.
For the range checks, just add a check to return zero if the value is out of range.
Here's an updated version with both fixes in place. Note this this version omits the strip("0")
call, which fixes the zero case:
class Solution(object):
def reverse(self, x):
sp = str(abs(x))[::-1]
ans = int(sp)
if x < 0:
ans = -ans
if ans < -2**31 or ans > 2**31 - 1:
return 0
return ans
This should handle all of the test cases correctly.