题目地址:
https://www.lintcode.com/problem/count-1-in-binary/description
给定一个位整数,求其二进制表示中的个数。可以用lowbit解决。其中lowbit(x) = x & -x
,指的是x
的二进制表示最右边的1
所代表的十进制数是几。这可以由-x = ~x + 1
得到。代码如下:
public class Solution {
/*
* @param num: An integer
* @return: An integer
*/
public int countOnes(int num) {
// write your code here
int res = 0;
while (num != 0) {
res++;
num -= lowbit(num);
}
return res;
}
private int lowbit(int x) {
return x & -x;
}
}
时间复杂度,空间。