机器采用二进制对数值进行表示、存储和运算
在程序中恰当地使用二进制,可以提高运行效率


相同为0,不同为1
也可用“不进位加法”来理解
异或运算的特点与应用:

二进制数的最右边为第0位
获取×在二进制下的第n位(0或者1) :(x >>n)& 1
将×在二进制下的第n位置为1:x |(1< 将×最右边的n位清零:x&(~0< 判断奇偶: . lowbit: https://leetcode.cn/problems/number-of-1-bits/ https://leetcode.cn/problems/power-of-two/ https://leetcode.cn/problems/reverse-bits/ https://leetcode.cn/problems/counting-bits/ 分享给大家:Linux,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,TCP/IP,协程,DPDK等技术内容,立即学习位运算实战要点
除以2的幂次:实战
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
while(n > 0){
if((n & 1) == 1) cnt++;
n = n >> 1;
}
return cnt;
}
};
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
for(int i = 0; i < 32; i++){
if((n >> i) & 1) cnt++;
}
return cnt;
}
};
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
while(n > 0){
cnt++;
n = n & (n - 1);
}
return cnt;
}
};
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & -n) == n;
}
};
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ans = 0;
for(int i = 0; i < 32; i++){
ans = (ans << 1) | (n >> i & 1);
}
return ans;
}
};
class Solution {
public:
vector<int> countBits(int n) {
vector<int> cnt(n + 1, 0);
for(int i = 1; i <= n; i++){
cnt[i] = cnt[i & (i - 1)] + 1;
}
return cnt;
}
};