Reputation: 2552
Using slice
method in Python
we are able to reverse strings and numbers easily. However, how could it be done when the number is negative?
def reverse(x):
string = str(x)
return int(string[::-1])
print(reverse(-123))
Gives an error as it returns 321-
EDIT:
Now let's have two more assumptions:
If the reversed number is not within [−2^31, 2^31 − 1]
it
should return 0.
For numbers like 120
, it should return 21
as its reverse.
Now, how can we reverse -120
into -21
?
Upvotes: 1
Views: 2349
Reputation: 97
I have posted the unwrapped, simplified code to make it easier to understand the answer:
def int_reverser(test):
if test >= 0:
answer = int(str(test)[::-1])
else:
answer = -int(str(-test)[::-1])
if -2**31 <= answer <= 2**31 - 1:
return answer
else:
return 0
Upvotes: 1
Reputation: 7313
You can check ,if your number is negative then add -
behind the output. You will get the expected output.
Therefore you code will be like:
def reverse(x):
y = ""
if int(x) <= -1:y="-";x = int(x)*-1
output = int(y+str(x)[::-1])
if output >= -2**31 and output <= 2**31 - 1:return output
else: return 0
print(reverse(-123))
Testing:
>>> reverse(-123)
-321
>>> reverse(123)
321
>>> reverse(-120)
-21
>>> reverse(120)
21
>>> reverse(123)
321
>>> reverse(-74634545484744)
0
>>> reverse(74634545484744)
0
It is also very simple and understandable.
Upvotes: 0
Reputation: 236114
Assuming that you want to preserve the sign, try this:
def reverse(x):
ans = int(str(x)[::-1]) if x >= 0 else -int(str(-x)[::-1])
return ans if -2**31 <= ans <= 2**31 - 1 else 0
It works as expected for all the edge cases introduced by the new requirements:
reverse(321)
=> 123
reverse(-321)
=> -123
reverse(120)
=> 21
reverse(-120)
=> -21
reverse(7463847412)
=> 2147483647
reverse(8463847412)
=> 0
reverse(-8463847412)
=> -2147483648
reverse(-9463847412)
=> 0
Upvotes: 6