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;}