题目描述
解题思路
求所有位数是否为一,那么就依次移动二进制数,往右移动,各位数是1,计数器加一,知道这个数被移动为0。
特别注意:这里的n移动需要是>>>,而不是>>,>>>是无符号移动,该数可能为负数,也就是符号位可能为1,所以需要将符号位一起移动。
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
if ((n & 1) == 1) count++;
n >>>= 1;
}
return count;
}
}
338. 比特位计数
和这道题类似,只不过这道题没有负数,移位也不需要考虑符号位,所以更简单!!!
class Solution {
public int[] countBits(int n) {
int[] array = new int[n + 1];
array[0] = 0;
for (int i = 1; i <= n; i++) {
int count = 0;
int temp = i;
while (temp != 0) {
if ((temp & 1) == 1) count++;
temp >>= 1;
}
array[i] = count;
}
return array;
}
}