题目
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为 汉明重量)。
代码实现
位运算
如果低位很多0,效率会很低
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
int temp;
while (n != 0){
temp = n & 1;
if (temp != 0){
res++;
}
n >>>= 1;
}
return res;
}
}
位运算——巧用n&(~n+1)
n&(~n+1)得到最右边的第一个1,再用n和它异或消去最右边的1
每次消去n最右边的1
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
//得到第一个1
int bit = n & (~n + 1);
while (bit != 0){
res++;
//n异或每次得到的右边第一个1即消去这个1
n ^= bit;
//
bit = n & (~n + 1);
}
return res;
}
}
位运算——巧用n &= n - 1
n &= n - 1每次消去n最右边的1,还可以用来判断数是否是2的幂次方
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res++;
n &= n - 1;
}
return res;
}
}