Python “Reverse Integer”问题求解答

2015-01-20 22:55:47 +08:00
 imkh
在LeetCode上有一道“Reverse Integer”的题 ,https://oj.leetcode.com/problems/reverse-integer/
但用Python解决时会出现下面的问题,该怎么解答呢?
```python
class Solution:
# @return an integer
def reverse(self, x):
if x >= 0 :
return int(str(x)[::-1])
else:
return -1*int(str(-1*x)[::-1])
Submission Result: Wrong Answer
```
Input: 1534236469
Output: 9646324351
Expected: 0

Python里,当int溢出时,不是会自动类型转换为long吗?
那这道题该怎么做才能提交?
4280 次点击
所在节点    Python
5 条回复
virusdefender
2015-01-20 23:03:01 +08:00
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

你没看提示啊
virusdefender
2015-01-20 23:05:08 +08:00
python 的话也要按照32位数来算
imkh
2015-01-20 23:06:23 +08:00
@virusdefender 那怎样按照32位数来算?
virusdefender
2015-01-20 23:14:25 +08:00
@imkh 判断一下是不是超过32位数的范围啊

imkh
2015-01-20 23:41:06 +08:00
@virusdefender 感谢。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/163967

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX