本文介紹幾種差用的位操作:
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的最后一個(gè)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的例子
可以用來計(jì)算n有幾個(gè)1怀读。
// 記錄數(shù)字中1的位數(shù)
int bitCount(int n) {
int count = 0;
// 數(shù)字的二進(jìn)制表示中有多少個(gè)1就進(jìn)行多少次操作
while (n != 0) {
// 從最右邊的1開始,每一次操作都使n的最右的一個(gè)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/ - 推薦