在 Python 中反转负数

lon*_*ome 1 python slice

使用中的slice方法Python我们可以轻松地反转字符串和数字。但是,当数字为负数时怎么办?

def reverse(x):
    string = str(x)
    return int(string[::-1])

print(reverse(-123))
Run Code Online (Sandbox Code Playgroud)

返回时出现错误 321-

编辑:

现在让我们再做两个假设:

  1. 如果反转数不在[?2^31, 2^31 ? 1]其中,则应返回 0。

  2. 对于像 那样的数字120,它应该21以相反的形式返回。

现在,我们怎样才能逆转-120-21

Ósc*_*pez 6

假设你想保留标志,试试这个:

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
Run Code Online (Sandbox Code Playgroud)

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

reverse(321)
=> 123
reverse(-321)
=> -123
reverse(120)
=> 21
reverse(-120)
=> -21
reverse(7463847412)
=> 2147483647
reverse(8463847412)
=> 0
reverse(-8463847412)
=> -2147483648
reverse(-9463847412)
=> 0
Run Code Online (Sandbox Code Playgroud)