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里面一位兄弟的算法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值