Sword refers to Offer65. No need to add, subtract, multiply and divide for addition

1. Bit operation:
convert a+b into a carry part + a non-carry part;
carry part: find a place where the corresponding binary digits of a and b are both 1 (using &), and then <<1, which is equivalent carry operation;
not carry section: a ^ b itself is referred to not carry adder;
with a and b represent the carry section and do not carry section, continuous cycle, until one is 0, the other is a + b;
the So choose b as the loop condition, because b must eventually become 0: if there are k 0s at the end of the binary of b, then b = (a & b) << 1 has at least k+1 0s, so at most 2 loops b It must be 0; and if a is to be 0, a == b must be required. This situation does not happen every time;

class Solution {
    
    
public:
    int add(int a, int b) {
    
    
        while (b) {
    
    
        	//这里转成unsigned, 因为负数左移补1,而我们想让它补0
            int c = unsigned(a & b) << 1;//进位部分,即对应二进制位是1 1时,使用&找到1 1 的位,之后 << 1将其加到前一位上
            a ^= b;//不进位部分:对应二进制位是1 0得1,0 1得1,0 0得0,1 1得0,因此用 ^
            b = c;//相当于将求a+b转换为求进位部分+不进位部分,但转换之后相加依然可能需要进位,因此循环至其中一部分为0停止
        }
        return a;
    }
};

Guess you like

Origin blog.csdn.net/jiuri1005/article/details/114490430