描述:
計算在一個 32 位的整數的二進制表式中有多少個 1
.
給定 32
(100000),返回 1
給定 5
(101),返回 2
給定 1023
(111111111),返回 9
分析:
要獲得一個整數的二進制有多少個“1”,需要知道整數是通過除2取餘來獲得該整數的二進制。所以可以採用一個計數器,對num循環除2取餘數,如果餘數爲“1”,計數器加1,獲得該整數的二進制中“1”的個數
代碼實現:
public int countOnes(int num) {
// write your code here
int count = 0;
//如果num小於0需要將num轉換成無符號整數
if(num<0){
long unum = num & Integer.MAX_VALUE;
unum |= 0x80000000L;
while(unum>0){
if(unum%2==1){
count++;
}
unum/=2;
}
}else{
while(num>0){
if(num%2==1){
count++;
}
num/=2;
}
}
return count;
}