Sword refers to Offer 65-do not add, subtract, multiply and divide for addition C++


2021/2/6 Second brush
Boundary judgment: the calculation stops when the carry is merged to 0.
Loop: In each round, a is the current non-carry close, and b is the current carry close. Since b will change, the result of the non-carry combination must be stored first.

 while(b) {
    
    
            //非进位合
            int res = a ^ b;
            b = (unsigned int)(a & b) << 1;
            a = res;
        }

The final result: res is a


Title description

Insert picture description here

Bit operation

1. Decimal
19 + 8 = 17 + 10
131 + 79 = 900 + 110 = 10 + 1000 = 1010
When writing an addition operation on scratch paper, we will directly move the carry to the previous digit +1, but in fact the addition is Going through such a process.
All additions are calculated by first calculating the non-carry sum and then adding the carry sum.
Insert picture description here
Suppose the non-carry is combined to n, and the carry is combined to c,
Insert picture description here
and then the problem may appear negative. What should we do? In fact, as long as the computer's complement addition and subtraction calculation is correct, we are correct in this way.
Also, C++ in LeetCode does not support shifting negative numbers to the left, so it needs to be turned into an unsigned integer. I don’t understand exactly what unsigned int is like and what is going on with negative numbers.

class Solution {
    
    
public:
    int add(int a, int b) {
    
    
        while(b != 0) {
    
    
            //此轮非进位合
            int res = a ^ b;
            //此轮进位合
            b = (unsigned int)(a & b) << 1;
            //更新a为此轮非进位合,继续与进位合进行运算
            a = res; 
        }
        return a;
    }
};

Insert picture description here
Time complexity O(1)
Space complexity O(1)

Guess you like

Origin blog.csdn.net/qq_42883222/article/details/112793807