python - 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:
If the reversed number is not within
[−2^31, 2^31 − 1]
it should return 0.For numbers like
120
, it should return21
as its reverse.
Now, how can we reverse -120
into -21
?
解决方案
假设您要保留标志,请尝试以下操作:
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
推荐阅读
- elastic-stack - ELK,文件节拍从消息中删除了一些文本
- python - 生产中的观察者设计模式如何表现?
- c# - SonarQube MSBuild 运行程序中的程序化覆盖排除
- java - 添加子字符串以省略部分输出
- .net - 用 jwt 交换访问令牌返回 invalid_grant 错误
- javascript - PHP函数中的Jquery - 数字格式
- html - 重新渲染时,Angular 5 Datatables 会弹出警告警报
- visual-studio-2017 - Visual Studio 2017 中的 nuget 包参考蓝色图标
- hyperledger-fabric - fabric-sdk-go 连接失败
- sql - 从组合框/文本框选择中插入 SQL