public static int getOneCount(int num) {
/**
* 思路为:每次向右移动一位,然后与1相与,
* */
int oneCount = 0;
do {
if((num & 1) != 0){
++oneCount;
}
} while ((num >>>= 1) != 0);
/**必须用num>>>=1(无符号右移),而不能用num>>=1(有符号右移),
* 因为当参数为负数时,有符号右移总是在高位插入1,导致死循环 **/
return oneCount;
}
转载于:https://my.oschina.net/u/1155515/blog/263970