欧美极品高清xxxxhd,国产日产欧美最新,无码AV国产东京热AV无码,国产精品人与动性XXX,国产传媒亚洲综合一区二区,四库影院永久国产精品,毛片免费免费高清视频,福利所导航夜趣136

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

作者: xiaos    時間: 2015-4-10 16:52
標(biāo)題: 二進(jìn)制數(shù)中1的個數(shù)
看到這樣一個題目,感覺充分的體現(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;
}






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