注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example :
Given a = 1 and b = 2, return 3.
class Solution {
public:
int getSum(int a, int b) {
return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
}
};
https://discuss.leetcode.com/topic/50315/a-summary-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently
补充位运算符相关知识:
Set negation ALL_BITS ^ A or ~A
Set bit A |= 1 << bit
Clear bit A &= ~(1 << bit)
Test bit (A & 1 << bit) != 0
Extract last bit A&-A or A&~(A-1) or x^(x&(x-1))
Remove last bit A&(A-1)
Get all 1-bits ~0
Examples
//Count the number of ones in the binary representation of the given number
int count_one(int n) {
while(n) {
n = n&(n-1);
count++;
}
return count;
}
//Is power of four (actually map-checking, iterative and recursive methods can do the same)
bool isPowerOfFour(int n) {
return !(n&(n-1)) && (n&0x55555555);
//check the 1-bit location;
}