0
点赞
收藏
分享

微信扫一扫

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

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

** AddressSanitizer 工具,会对有符号数的左移位操作做保护,强制转成无符号数做移位可绕过。**

负数左移的时候会出问题但是编译的时候不报错

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

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


举报

相关推荐

0 条评论