原文来源于网络,已经无法考证出处,我将原文进行了一个理解性的翻译和总结:
- Set union A | B 并集
- Set intersection A & B 交集
- Set subtraction A & ~B 求差集
- Set negation ~A 取反
- Set bit A |= 1 << bit 将某一位置1
- Clear bit A &= ~(1 << bit) 将某一位置0
- Test bit (A & 1 << bit) != 0 测试某一位是否为1
- Remove last bit A&(A-1) 清除最右边的一个1
- Extract last bit A&-A or A&~(A-1) or x^(x&(x-1)) 提取出来最右边的一个1
- Get all 1-bits ~0 拿到所有位全是1的值
Examples
Count the number of ones in the binary representation of the given number 求1的个数
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) 求是否是4的次方数
bool isPowerOfFour(int n) {
return !(n&(n-1)) && (n&0x55555555);
//check the 1-bit location;
}
^ tricks
Sum of Two Integers
int getSum(int a, int b) {
return b==0? a:getSum(a^b, (a&b)<<1); //be careful about the terminating condition;
}
Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] return 2. (Of course, you can do this by math.)
int missingNumber(vector<int>& nums) {
int ret = 0;
for(int i = 0; i < nums.size(); ++i) {
ret ^= i;
ret ^= nums[i];
}
return ret^=nums.size();
}
| tricks
Keep as many 1-bits as possible
求<=给定的数的2的幂
Find the largest power of 2 (most significant bit in binary form), which is less than or equal to the given number N.
将连续的两位置1,将连续的四位置1,直到将连续的32位置1。最后结果右移。
long largest_power(long N) {
//changing all right side bits to 1.
N = N | (N>>1);
N = N | (N>>2);
N = N | (N>>4);
N = N | (N>>8);
N = N | (N>>16);
return (N+1)>>1;
}
Reverse Bits
Reverse bits o