標(biāo)題: 二進(jìn)制數(shù)中1的個(gè)數(shù) [打印本頁]

作者: xiaos    時(shí)間: 2015-4-10 16:52
標(biāo)題: 二進(jìn)制數(shù)中1的個(gè)數(shù)
看到這樣一個(gè)題目,感覺充分的體現(xiàn)了位運(yùn)算的便捷
題目來源:劍指Offer
題目表述:寫這樣一個(gè)函數(shù):對(duì)于輸入給定的一個(gè)整數(shù),要求輸出該整數(shù)二進(jìn)制碼中1的個(gè)數(shù)
錯(cuò)誤解法:當(dāng)輸入為負(fù)數(shù)時(shí),會(huì)導(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ù)對(duì)應(yīng)的二進(jìn)制中1的個(gè)數(shù)
int NumberOf1(int n)
{
    int count = 0;
    while(n)
    {
        count ++;
        n = (n-1) & n;
    }
    return count;
}






歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1