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
latteczy
V2EX  ›  Python

Python 实现不用加减乘除做加法,输入负数无结果。

  •  
  •   latteczy · 2015-06-03 20:06:21 +08:00 · 5743 次点击
    这是一个创建于 3256 天前的主题,其中的信息可能已经有所发展或是发生改变。
    def Add(n1,n2):
        carry=1
        while carry!=0:
            s = n1^n2
            carry = (n1&n2)<<1
            n1 = s
            n2 = carry
        return n1
    

    按照这个思路用c++和java写都没有问题,但是用Python时输入负数就不行。问题应该出在carry这个地方,我打印了一下一直递增,不会出现0。不知道为什么?

    9 条回复    2015-06-04 11:10:41 +08:00
    BuilderQiu
        1
    BuilderQiu  
       2015-06-03 21:22:31 +08:00
    C++、Java会溢出

    > Python的整型数据的位宽是32位,8个字节。int 最大值是2147483647 (sys.maxint),而long 长度仅受内存大小限制。
    > 溢出的int整数操作结果升级为long类

    传送门:
    http://www.cnblogs.com/zhengyun_ustc/archive/2009/10/14/shifting.html
    arbipher
        2
    arbipher  
       2015-06-03 21:25:22 +08:00
    看标题还以为是自然数的递归定义。。。
    latteczy
        3
    latteczy  
    OP
       2015-06-03 22:09:03 +08:00
    @BuilderQiu
    是要将(n1&n2)强制类型转换为long吗?试过之后还是不可以。
    oott123
        4
    oott123  
       2015-06-03 22:28:38 +08:00 via Android
    为啥要用 Python 做这种事情…
    czheo
        5
    czheo  
       2015-06-03 22:30:50 +08:00
    @oott123 why not?
    xiazi
        6
    xiazi  
       2015-06-04 00:27:24 +08:00
    @oott123 可以让别人看不懂你的代码
    czheo
        7
    czheo  
       2015-06-04 00:59:47 +08:00
    (n1&n2)<<1这一步int overflow的时候,python会自动转成long。解决方法如下。
    http://stackoverflow.com/questions/7201207/python-bitshift-32-bit-constraint
    recall704
        8
    recall704  
       2015-06-04 09:39:25 +08:00
    @BuilderQiu 少年,32bit 不是 4字节么?咋变成8字节了
    BuilderQiu
        9
    BuilderQiu  
       2015-06-04 11:10:41 +08:00
    @recall704
    按说32bit的话是4字节 4x8 ...
    我那是直接引用的查询到的文章里面的。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2352 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 13:48 · PVG 21:48 · LAX 06:48 · JFK 09:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.