- 题目:请实现一个函数,输入一个整数,输出该整二进制表示中1的个数。例如把9表示成2进制是1001,有2位是1。因此如果输入9,该函数输出2.
- 代码如下:
public class offer243 {
public static int numberOf1(int n){
int count=0;
while (n!=0){
count++;
n=(n-1)&n;
}
return count;
}
public static void main(String[] args) {
System.out.println(numberOf1(9));
}
}
github代码地址:https://github.com/iot-wangshuyu/offer/blob/master/code/src/offer243.java