Why this code for addition(using bitwise operation) works in java

后端 未结 5 1653
南旧
南旧 2020-12-31 09:16
public int add(int a, int b){  
        while (b != 0){
            int carry = (a & b) ;

            a = a ^ b; 

            b = carry << 1;
        }
          


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-31 10:06

    It relies on the fact that 1+1=10 (bitwise), i.e. "if an addition implies a carry bit, then sum current's digit column must be zero". Think of the "<<" operator as "carry the bits to the left" instead of thinking "multiply an int by 2"

    Here's a prosaic description of the code.

    carry = Ignore those bits that will produce carry bits (because their sum in the current "column"  will be 0), but collect the carry bits. 
    a = Add those bits of a and b that won't produce a carry bit (i.e. use XOR)
    b = Carry the carry bits one column left.
    

提交回复
热议问题