常见的bit操作
Swap variable without temp
using XOR
int x = 10, y = 5;
x = x ^ y; // x become 15
y = x ^ y; // y became 10;
x = x ^ y; // x become 5.
Number of 1 Bits
计算一个无符号数的二进制表达里面有多少位的值是1,也就是计算它的Hamming weight。
做法很直观,就是用这个数不断和一个只有当前位为1的数进行and操作, check whether the result is 0,遍历int的所有32位。
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
for(int i = 0; i < 32; i++) {
// 结果不是1
if((n & (1 << i)) != 0) {
count++;
}
}
return count;
}
}