Sword refers to Offer ------ No need to add, subtract, multiply and divide for addition

Insert picture description here
Topic link!

Ideas:
This question

The picture comes from here!

Code:

class Solution {
    
    
public:
    int add(int a, int b) {
    
    
        if (a == 0 || b == 0) {
    
    
            return a == 0 ? b : a;
        }

       
        int sum = 0, carry = 0;

        while (b != 0) {
    
     // 当没有进位的时候退出循环
            sum = a ^ b; 
            carry = (unsigned int) (a & b) << 1; //Leetcode C++ 不允许负数进行左移操作,故要加 unsigned int,其他的编译器是可以的对负数进行左移

            a = sum;
            b = carry;
        }

        return a;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/115271648