[LeetCode] Bit 操作

本文介紹幾種差用的位操作:

n = n & (-n)

n = n & (-n) 能取出最右端為'1'的位。比如:
22 =
0000 0000 0000 0000 0000 0000 0001 0110
-21 =
1111 1111 1111 1111 1111 1111 1110 1001 (先各位取反,包括符號位)
1111 1111 1111 1111 1111 1111 1110 1010 (再末位+1)
21 & (-21) =
0000 0000 0000 0000 0000 0000 0000 0010
21的最后一個1保留,其他全部為0。

相關(guān)題目

260 Single Number III
https://leetcode.com/problems/single-number-iii/solution/

n = n & (n – 1)

n & (n – 1) 總是能清除最后一位bit。比如:n=112


n=112的例子

可以用來計算n有幾個1。

// 記錄數(shù)字中1的位數(shù)  
int bitCount(int n) {
    int count = 0;
    // 數(shù)字的二進(jìn)制表示中有多少個1就進(jìn)行多少次操作  
    while (n != 0) {
        // 從最右邊的1開始,每一次操作都使n的最右的一個1變成了0,即使是符號位也會進(jìn)行操作。  
        n &= n - 1;
        count++;
    }
    return count;
}

相關(guān)題目

231 Power of Two
https://leetcode.com/problems/power-of-two/


本文參考:https://tech.liuchao.me/2016/11/count-bits-of-integer/ - 推薦

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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