public static int countBinNum2(int num){
/*
* 改进了算法
* 因为补码加上原码==pow(2,这个数的绝对值所换算成二进制的位数)
* 利用负数所表示例如-5 == 1111 1111 1111 1111 1111 1111 1111 1111(0xffff)
5 == 101 反码 010 +1 ==补码 011 ..1111 1011
* */
if (num ==0){return 0;}
int m=0,count =0,tureNum = Math.abs(num);
while (Math.pow(2,m)<=tureNum){
m++;
}
if (num>0)
{
for (int i=0;i<m;i++){
if (num%2==1){count++;}
num = num/2;
}
return count;
}
int change = (int)(Math.pow(2,m)+num),changeBinCount=0;
for (int i=0;i<m;i++){
if (change%2==1){changeBinCount++;}
change = change/2;
}
return (32-m+changeBinCount);
}
/*
下面这个是利用位运算符求解的
*/
public static int countBinNum3(int num){
int count = 0;
while (num != 0) {
num = num & (num - 1);
count++;
}
return count;
}