剑指offer65 (Leetcode 371) 两整数之和
解法一:基于递归和二进制异或的方法
class Solution {
public:
int getSum(int a, int b) { //假设a=3,b=5
int sum, c;
sum = a ^ b; //3^5=0000 0011 ^ 0000 0101 = 0000 0110
c = ((unsigned int)(a & b)) << 1; //3&5=0000 0011 & 0000 0101 = 0000 0001 再左移一位为0000 0010
if (c != 0) {
return getSum(sum, c);
}
return sum;
}
};
解法二:基于迭代和二进制异或的方法
class Solution2 {
public:
int getSum(int a, int b) {
while (b != 0) {
int c = a & b;
a = a ^ b;
b = (unsigned int)c << 1;
}
return a;
}
};
解法一:基于递归和二进制异或的方法
class Solution {
public:
int getSum(int a, int b) { //假设a=3,b=5
int sum, c;
sum = a ^ b; //3^5=0000 0011 ^ 0000 0101 = 0000 0110
c = ((unsigned int)(a & b)) << 1; //3&5=0000 0011 & 0000 0101 = 0000 0001 再左移一位为0000 0010
if (c != 0) {
return getSum(sum, c);
}
return sum;
}
};
解法二:基于迭代和二进制异或的方法
class Solution2 {
public:
int getSum(int a, int b) {
while (b != 0) {
int c = a & b;
a = a ^ b;
b = (unsigned int)c << 1;
}
return a;
}
};
2020-04-20
在牛客打卡11天,今天学习:刷题 5 道/代码提交 5 次
全部评论
相关推荐
10-30 17:07
University of California Riverside UE4 点赞 评论 收藏
分享