位移
/**
* 剑指 Offer 15. 二进制中1的个数
* https://leetcode.cn/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/
*
* 思路:位移
* */
public class Solution1 {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count += n & 1; // 判断最低位是否是 1
n = n >>> 1; // 无符号右移
}
return count;
}
}
位运算
/**
* 剑指 Offer 15. 二进制中1的个数
* https://leetcode.cn/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/
*
* 思路:位运算
* 110100
* 110011 &
* */
public class Solution2 {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n &= n - 1; // 消掉最低位的 1
count++;
}
return count;
}
}