LeetCode 371 Sum of Two Integers

Tag: 位操作 LeetCode Posted on 2022-03-08 19:15:35 Edited on 2022-03-08 19:22:58 Views: 140

概述

https://leetcode.com/problems/sum-of-two-integers/

剑指 Offer 原题: https://iamazing.cn/page/sword-offer-65

位运算

实现的时候注意,左移优先级比 & 高!

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

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