Add two integers using only bitwise operators?

后端 未结 7 1269
遇见更好的自我
遇见更好的自我 2020-11-27 12:41

In C#, is it possible to perform a sum of two 32-bit integers without using things like if..else, loops etc?

That is, can it be done using only the bitwise operation

7条回答
  •  我在风中等你
    2020-11-27 13:25

    Try this:

        private int add(int a, int b) {
            if(b == 0)
                return a;
    
            return add( a ^ b, (a & b) << 1);
        }
    

    Edit: Corrected if statement

提交回复
热议问题