Simulating integer overflow in Python

前端 未结 5 1488
無奈伤痛
無奈伤痛 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 19:04

    I think the basic idea is sound, but needs some tweaks:

    1. your function doesn't overflow on sys.maxint+1, but it should;
    2. sys.maxint can be exceeded several times over as a result of a single operation;
    3. negative values below -sys.maxint-1 also need to be considered.

    With this in mind, I came up with the following:

    import sys
    
    def int_overflow(val):
      if not -sys.maxint-1 <= val <= sys.maxint:
        val = (val + (sys.maxint + 1)) % (2 * (sys.maxint + 1)) - sys.maxint - 1
      return val
    

提交回复
热议问题