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

后端 未结 22 1712
情书的邮戳
情书的邮戳 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:47

    It is my implementation on Python. It works well, when we know the number of bytes(or bits).

    def summ(a, b):
        #for 4 bytes(or 4*8 bits)
        max_num = 0xFFFFFFFF
        while a != 0:
            a, b = ((a & b) << 1),  (a ^ b)
            if a > max_num:
                b = (b&max_num) 
                break
        return b
    

提交回复
热议问题