劍指offer--11. 二進(jìn)制中1的個(gè)數(shù)

題目:
輸入一個(gè)整數(shù),輸出該數(shù)二進(jìn)制表示中1的個(gè)數(shù)。其中負(fù)數(shù)用補(bǔ)碼表示

思路:
二進(jìn)制數(shù)每位挨個(gè)和 1 (左移后其實(shí)不是1了,如:000100 ) 做與(&)運(yùn)算,結(jié)果不是零則count++

public class Solution {
    public int NumberOf1(int n) {
        if(n == 0)
            return 0;
        int count = 0;
        int temp = 1;
        while(temp != 0){
            if((temp & n) != 0)
                count ++;
            temp = temp << 1;
        }
        return count;
    }
}

如果移位的不是 1 而是 n 的話,要注意負(fù)數(shù)(補(bǔ)碼)向右移位時(shí)最左端會(huì)補(bǔ)1,這樣就死循環(huán)了,解決方法時(shí)把 n = n >> 1 改成 n = n >>>1,">>>" 無視符號(hào)位移位

public class Solution {
    public int NumberOf1(int n) {
        if(n == 0)
            return 0;
        int count = 0;
        while(n != 0){
            if((n & 1) == 1)
                count++;
            n = n >>> 1; // 無視符號(hào)位右移
        }
        return count;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容