简体   繁体   English

在 Python 中反转负数

[英]Reversing a negative number in Python

Using slice method in Python we are able to reverse strings and numbers easily.Python使用slice方法,我们可以轻松地反转字符串和数字。 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-返回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^31, 2^31 − 1] ,则应返回 0。

  2. For numbers like 120 , it should return 21 as its reverse.对于像120这样的数字,它应该返回21作为它的反向。

Now, how can we reverse -120 into -21 ?现在,我们如何将-120反转为-21

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

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

Edited已编辑

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.它也非常简单易懂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM