python 整数越界问题

 python 内部自带大整数运算能力,整数运算不会溢出,只要内存足够,就oK

下面的例子演示了两个32位整数加法的情况(通过位运算实现),为了模拟溢出的效果,必须人工的进行位运算,~运算符除了求反,还是二进制的补运算符,运算过后的二进制数字按照补码解释,例如 ~(0011 1100) = (1100 0011) = -61

def getSum(a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        MAX = 0X7fffffff
        MIN = 0X80000000
        while b != 0 :
          a,b = a^b,(a&b)<<1
          print(" a = {0:b},b =  {1:b}".format(a,b))
        return a 
def getSum_(a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        MAX = 0x7FFFFFFF
        MIN = 0x80000000
        mask = 0xFFFFFFFF
        while b != 0:
            a, b = (a ^ b) & mask, ((a & b) << 1) & mask
            print(type(a))
            print(" a = {0:b},b =  {1:b}".format(a,b))
        return a if a <= MAX else ~(a^mask)
     
print(getSum_(-1,-1))
print(getSum(-1,1))

    原文作者:大整数乘法问题
    原文地址: https://blog.csdn.net/man_sion/article/details/72510284
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞