二进制的位操作
常用的二进制内置函数
int __builtin_ctz(unsigned int x);
int __builtin_ctzll(unsigned long long x);
// 返回 x 二进制表示下最低位的1后面有多少个0
int __builtin_popcount(unsigned int x);
int __builtin_popcountll(unsigned long long x);
// 返回 x 二进制表示下有多少个1
成对变换
对于非负整数 n n n而言:
- n = 2 k n=2k n=2k时, n x o r 1 n \ xor 1 n xor1等于 n + 1 n+1 n+1
- n = 2 k + 1 n=2k+1 n=2k+1时, n x o r 1 n \ xor 1 n xor1等于 n − 1 n-1 n−1
l o w b i t lowbit lowbit运算
int lowbit(int x) {
return x & (-x);} // 返回最低位的1及其后边所有的0
比如, n = 10 = ( 1010 ) 2 , l o w b i t ( n ) = ( 10 ) 2 = 2 n=10=(1010)_2, \ lowbit(n)=(10)_2=2 n=10=(1010)2, lowbit(n)=(10)2=2
技巧使用:搭配树状数组,搭配 H a s h Hash Hash找到整数 x x x在二进制表示下所有的1的位(下面为解决代码)
int H[37], x;
cin >> x;
for(int i = 0; i < 36; i++) {
H[(1ll << i) % 37] = i;}
while(cin >> x) {
while(x > 0) {
cout << H[lowbit(x) % 37] << ' ';
x -= lowbit(x);
}
cout << endl;
}