題目地址:
https://www.lintcode.com/problem/number-of-1-bits/description
給定一個數,求其二進制表示中的個數。可以用lowbit解決。其中lowbit(x) = x & -x
,指的是x
的二進制表示最右邊的1
所代表的十進制數是幾。這可以由-x = ~x + 1
得到。代碼如下:
public class Solution {
/**
* @param n: an unsigned integer
* @return: the number of ’1' bits
*/
public int hammingWeight(int n) {
// write your code here
int res = 0;
while (n != 0) {
res++;
n -= lowbit(n);
}
return res;
}
private int lowbit(int x) {
return x & -x;
}
}
時間複雜度,空間。