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

标签: 剑指 Offer 发布于:2022-02-28 10:50:00 编辑于:2022-02-28 10:50:00 浏览量:841

概述

https://leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof/

位运算实现加法

https://www.jianshu.com/p/7bba031b11e7

由于 C++ 中禁止对负数左移(runtime error: left shift of negative value),所以我们在左移前需要进行类型转换。

class Solution {
public:
    int add(int a, int b) {
        int sum = a ^ b;
        int carry = (unsigned int) (a & b) << 1;
        if (carry == 0) return sum;
        else return add(sum, carry);
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/