What is the best way to add two numbers without using the + operator?

后端 未结 22 1704
情书的邮戳
情书的邮戳 2020-11-27 05:18

A friend and I are going back and forth with brain-teasers and I have no idea how to solve this one. My assumption is that it\'s possible with some bitwise operators, but n

22条回答
  •  佛祖请我去吃肉
    2020-11-27 05:34

    Go based solution

    func add(a int, b int) int {
    
    for {
        carry := (a & b) << 1
        a = a ^ b
        b = carry 
        if b == 0 {
            break
        }
    }
    
    return a 
    
    }
    

    same solution can be implemented in Python as follows, but there is some problem about number represent in Python, Python has more than 32 bits for integers. so we will use a mask to obtain the last 32 bits.

    Eg: if we don't use mask we won't get the result for numbers (-1,1)

    def add(a,b):   
        mask = 0xffffffff
    
        while b & mask:
            carry = a & b
            a = a ^ b
            b = carry << 1
    
        return (a & mask)
    

提交回复
热议问题