|
看到這樣一個題目,感覺充分的體現(xiàn)了位運算的便捷
題目來源:劍指Offer
題目表述:寫這樣一個函數(shù):對于輸入給定的一個整數(shù),要求輸出該整數(shù)二進(jìn)制碼中1的個數(shù)
錯誤解法:當(dāng)輸入為負(fù)數(shù)時,會導(dǎo)致死循環(huán)
int NumberOf1(int n)
{
int count = 0;
while(count)
{
if(n & 1)
count ++;
n = n >> 1;
}
return count;
}
正確解法:循環(huán)次數(shù):整數(shù)所占長度
int NumberOf1(int n)
{
int count = 0;
int temp = 1;
while(temp)
{
if(temp & n)
count ++;
temp = temp << 1;
}
return count;
}
高效解法:循環(huán)次數(shù):整數(shù)對應(yīng)的二進(jìn)制中1的個數(shù)
int NumberOf1(int n)
{
int count = 0;
while(n)
{
count ++;
n = (n-1) & n;
}
return count;
}
|
|