LeetCode第371题(Sum of Two Integers)

Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to
use the operator + and -.

Example:

Given a = 1 and b = 2, return 3.

Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.

python代码

class Solution:
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        MAX = 0x7FFFFFFF    #7 = x111,x在第一位,是符号位
        MIN = 0x80000000    #8 = 1000,第一位的1表示负数
        mask = 0xFFFFFFFF    #掩码为全1
        while b:
            #a为无进位的相加结果,b为进位位
            a, b = (a ^ b) & mask, ((a & b) << 1) & mask
        """
        如果a在MAX的范围内,即a为正数(负数的判定为a >= MIN),返回a,
        否则按位运算后再返回a(此时a为负数,需要进行位运算符号位才有意义,
        而"~(a^mask)"这样的式子本身不改变a的值)
        """
        return a if a <= MAX else ~(a ^ mask)

PS:这段代码是借用leetcode里discussion里面一位兄弟的算法

猜你喜欢

转载自blog.csdn.net/ax478/article/details/79774385