V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
imkh
V2EX  ›  Python

Python “Reverse Integer”问题求解答

  •  
  •   imkh · 2015-01-20 22:55:47 +08:00 · 4327 次点击
    这是一个创建于 3586 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在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吗?
    那这道题该怎么做才能提交?
    第 1 条附言  ·  2015-01-20 23:40:54 +08:00
    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
    5 条回复    2015-01-20 23:41:06 +08:00
    virusdefender
        1
    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
        2
    virusdefender  
       2015-01-20 23:05:08 +08:00
    python 的话也要按照32位数来算
    imkh
        3
    imkh  
    OP
       2015-01-20 23:06:23 +08:00
    @virusdefender 那怎样按照32位数来算?
    virusdefender
        4
    virusdefender  
       2015-01-20 23:14:25 +08:00   ❤️ 1
    @imkh 判断一下是不是超过32位数的范围啊

    imkh
        5
    imkh  
    OP
       2015-01-20 23:41:06 +08:00
    @virusdefender 感谢。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1902 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 16:31 · PVG 00:31 · LAX 08:31 · JFK 11:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.