剑指 Offer ------ 不用加减乘除做加法

在这里插入图片描述
题目链接!

思路:
这道题

图片来自此处!

代码:

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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43743711/article/details/115271648
今日推荐