LC-371 Sum of Two Integers


def bin32(a):
    mask = 0xFFFFFFFF
    a &= mask
    res = ''
    i = 0
    while a != 0 or i < 32:
        res = str(a & 1) + res
        a >>= 1
        i += 1
    print(res)

def bin64(a):
    mask = 0xFFFFFFFFFFFFFFFF
    a &= mask
    res = ''
    i = 0
    while a != 0 or i < 64:
        res = str(a & 1) + res
        a >>= 1
        i += 1
    print(res)
class Solution(object):
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        # 32 bits integer max
        MAX = 0x7FFFFFFF
        # 32 bits interger min
        MIN = 0x80000000
        # mask to get last 32 bits
        mask = 0xFFFFFFFF
        bin32(a)
        bin32(b)
        while b != 0:
            # ^ get different bits and & gets double 1s, << moves carry
            a, b = (a ^ b) & mask, ((a & b) << 1) & mask
        bin32(a)
        bin64(a)
        bin64(~(a ^ mask))
        return a if a <= MAX else ~(a ^ mask)

class Solution(object):
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        # 32 bits integer max
        MAX = 0x7FFFFFFF
        # mask to get last 32 bits
        mask = 0xFFFFFFFF
        while b != 0:
            # ^ get different bits and & gets double 1s, << moves carry
            a, b = (a ^ b) & mask, ((a & b) << 1) & mask

        return a if a <= MAX else ~(a ^ mask)


# a > MAX, 就是 32bits的最高位为1,python会把这个数处理成正数,但是我们应该把它做为负数处理
# ~(a ^ mask)的目标就是把
# 0000000000000000000000000000000011111111111111111111111111101100 变成
# 1111111111111111111111111111111111111111111111111111111111101100

# res = Solution().getSum(1, 2)
# print(res)
#
# res = Solution().getSum(20, 30)
# print(res)
#
# res = Solution().getSum(-1, 1)
# print(res)

res = Solution().getSum(-12, -8)
print(res)


# bin32(2)
# bin32(~2)
# bin32(~2+1)
# bin32(-2) # -2 = ~2 + 1
#
# bin32(1)
# bin32(-1)
















最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容