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

 

 位运算模拟运算

  因为不熟悉,暂时照搬leetcode大佬题解

 

代码:

class Solution {
    public int add(int a, int b) {
        while(b != 0) { // 当进位为 0 时跳出
            int c = (a & b) << 1;  // c = 进位
            a ^= b; // a = 非进位和
            b = c; // b = 进位
        }
        return a;
    }
}

参考:https://leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof/solution/mian-shi-ti-65-bu-yong-jia-jian-cheng-chu-zuo-ji-7/
posted @ 2021-02-18 22:29  zjcfrancis  阅读(22)  评论(0编辑  收藏  举报