首页 > 解决方案 > Reversing a negative number in Python

问题描述

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:

  1. If the reversed number is not within [−2^31, 2^31 − 1] it should return 0.

  2. For numbers like 120, it should return 21 as its reverse.

Now, how can we reverse -120 into -21?

标签: pythonslice

解决方案


假设您要保留标志,请尝试以下操作:

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

对于新要求引入的所有边缘情况,它都按预期工作:

reverse(321)
=> 123
reverse(-321)
=> -123
reverse(120)
=> 21
reverse(-120)
=> -21
reverse(7463847412)
=> 2147483647
reverse(8463847412)
=> 0
reverse(-8463847412)
=> -2147483648
reverse(-9463847412)
=> 0

推荐阅读