1. 题目
2. 思路
(1) Integer.bitCount()
(2) 位运算
- n & (1 << i)会检查n的每一个二进制位上是否为1。
(3) 位运算优化
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public int hammingWeight(int n) {
return Integer.bitCount(n);
}
}
class Solution1 {
public int hammingWeight(int n) {
int count = 0;
for (int i = 0; i < 32; i++) {
if ((n & (1 << i)) != 0) {
count++;
}
}
return count;
}
}
class Solution2 {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n &= n - 1;
count++;
}
return count;
}
}