Write a function that takes an unsigned integer and returns the number of ’1' bits it has.
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011
, so the function should return 3.
思路:
不斷右移數(shù)字,與1,查找為1的個(gè)數(shù);或者mask不斷左移,左移不需要考慮算術(shù)右移或者邏輯右移的問(wèn)題。
public static int hammingWeight1(int n) {
int res = 0;
while (n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
public int hammingWeight(int n) {
int bits = 0;
int mask = 1;
for (int i = 0; i < 32; i++) {
if ((n & mask) != 0) {
bits++;
}
mask <<= 1;
}
return bits;
}
非按位查找,只找數(shù)字中是1的位,可以利用n&(n-1)會(huì)消去n最右邊1的特性。
public static int hammingWeight2(int n) {
int res = 0;
while (n != 0) {
res += 1;
n &= (n-1);
}
return res;
}