implement a plus b / a minus b without using any arithmetic operators

class Solution:
    """
    @param a: An integer
    @param b: An integer
    @return: The sum of a and b 
    """
    def aplusb(self, a, b):
        # write your code here
        if b == 0: return a

        s = a ^ b
        carry = (a & b) << 1

        return self.aplusb(s, carry)


        # a ^ b 得当前位的和
        # (a & b) 得当前位的进位
        # 当计算下一对二进制位的元素时,需要将当前进位左移一位

    # def aminusb(self, a, b):
    #     # a - b 
    #     # a + (-b)
    #     # -b = ~b + 1
    #     return self.aplusb(a, aplusb(~b, 1))

 

posted @ 2022-05-10 21:57  7aughing  阅读(18)  评论(0编辑  收藏  举报