leetcode 371. 两整数之和 机组二进制加法

https://leetcode-cn.com/problems/sum-of-two-integers/comments/
两数直接异或是无进位的加法器 得到A
两数直接做与操作是得到各个位的进位B
将A与B的二倍(左移一位 因为进位是要和前一位相加)再进行这样操作,直到进位为0

class Solution {
public:
    int getSum(int a, int b) {
        int ret = a^b;
        int carry = ((a & b)<<1);
        while(carry){
            a = ret;
            ret ^= carry;
            carry = ((a & carry)<<1);
        }
        return ret;
    }
};

在这里插入图片描述

** AddressSanitizer 工具,会对有符号数的左移位操作做保护,强制转成无符号数做移位可绕过。**
负数左移的时候会出问题但是编译的时候不报错
在这里插入图片描述

#include <iostream>
using namespace std;


class Solution {
public:
    int getSum(int a, int b) {
        while (b) {
            auto c = ((unsigned int)a & b) << 1; // 防止 AddressSanitizer 对有符号左移的溢出保护处理
            a = a ^ b;
            b = c;
        }
        return a;
    }
};

int main()
{
    Solution Solution1;
    cout<<Solution1.getSum(-1,1)<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值