Simulating integer overflow in Python

前端 未结 5 1496
無奈伤痛
無奈伤痛 2020-12-06 18:04

Python 2 has two integer datatypes int and long, and automatically converts between them as necessary, especially in order to avoid integer overflo

5条回答
  •  甜味超标
    2020-12-06 18:56

    Does your function use division or right bit-shifting? If not then you don't need to worry about overflows at each stage of the calculation because you will always get the "correct" answer modulo 2^32 or 2^64. Before returning the result (or before doing division or right bit-shifting) you can normalize back to the standard integer range using something like

    import sys
    
    HALF_N = sys.maxint + 1
    N = HALF_N * 2
    
    def normalize(value):
        return (value + HALF_N) % N - HALF_N
    

提交回复
热议问题