1. 题目
2. 思路
(1) 位运算
- 将原整数的二进制位不断进行无符号右移,并与1做与运算,若结果非0,则表示该位上为1。
(2) 位运算优化
- 一个非0整数与其减1的整数做与运算,会使二进制位最后一位1变成0。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public int hammingWeight(int n) {
int res = 0;
while (n != 0) {
if ((n & 1) != 0) {
res++;
}
n = n >>> 1;
}
return res;
}
}
class Solution1 {
public int hammingWeight(int n) {
int res = 0;
while (n != 0) {
res++;
n = n & (n - 1);
}
return res;
}
}