1,位翻轉 n^1 ,n 是0 或 1,和 1 異或后位翻轉了。
2, 判斷奇偶,n&1,即判斷最后一位是0還是1,如果結果為0,就是偶數,是1 就是奇數。
獲取 32 位二進制的 1 的個數,它會循環遍歷32次,判斷每一位的奇偶。
public int count1(int n) {int res = 0;while (n != 0) {res += (n & 1);n >>>= 1;}return res;}
3,n&(~n+1)? 獲取 n 最后的 1的數字,假設 n 為 110010,n&(~n+1) 就是 000010。
獲取 32 位二進制的 1 的個數,它會循環遍歷 n 中為 1 的個數的次數。
public int count3(int n) {int res = 0;while (n != 0) {n -= (n & (~n + 1));res++;}return res;}
4,n&(n-1), 它會刪除 n 中最后一個1 。比如 n 為 100110,n&(n-1) 為 100100。
?獲取 32 位二進制的 1 的個數,它會循環遍歷 n 中為 1 的個數的次數。
public int count2(int n) {int res = 0;while (n != 0) {n = (n & (n - 1));res++;}return res;}