将 x 最右边的 n 位清零, x & ( ~0 << n )
获取 x 的第 n 位值(0 或者 1),(x >> n) & 1
获取 x 的第 n 位的幂值,x & (1 << (n - 1))
仅将第 n 位置为 1,x | (1 << n)
仅将第 n 位置为 0,x & (~(1 << n))
将 x 最⾼位⾄第 n 位(含)清零,x & ((1 << n) - 1)
将第 n 位⾄第 0 位(含)清零,x & (~((1 << (n + 1)) - 1))
X & 1 == 1 判断是否是奇数(偶数)
X & = (X - 1) 将最低位(LSB)的 1 清零
X & -X 得到最低位(LSB)的 1
X & ~X = 0
class Solution {
public int missingNumber(int[] nums) {
int n = 0;
int _n = nums.length;
for (int i = 0; i < nums.length; i ++) {
n ^= nums[i];
_n ^= i;
}
return n ^ _n;
}
}
class Solution {
public int[] singleNumber(int[] nums) {
int[] ans = new int[2];
int x = 0;
for (int i = 0; i < nums.length; i ++) {
x ^= nums[i];
}
// X & -X 得到最低位(LSB)的 1
int n = x & -x; //记录出现了1的位置
for (int i = 0; i < nums.length; i ++) {
int tmp = nums[i] & n;
if (tmp == n) {
ans[0] ^= nums[i];
} else {
ans[1] ^= nums[i];
}
}
return ans;
}
}
201. 数字范围按位与
方法一
class Solution {
public int rangeBitwiseAnd(int m, int n) {
int d = n - m;
int p = 1;
int ans = m & n;
for (int i = 0; i < 31; i ++) {
if (d >= p) ans &= ~p;
else break;
p = p * 2;
}
return ans;
}
}
方法二
class Solution {
public int rangeBitwiseAnd(int m, int n) {
if (n == m) return n;
int _m = m;
int k = 0;
while (_m > 0) {
_m /= 2;
k ++;
}
if (n >= Math.pow(2, k)) return 0;
int ans = m ++;
while (m <= n) {
if (m == n || ans == 0) {
ans &= m;
break;
}
ans &= m ++ & n --;
}
return ans;
}
}
class Solution {
public int[] countBits(int num) {
int[] ans = new int[num + 1];
ans[0] = 0;
if (num == 0) return ans;
ans[1] = 1;
for (int i = 2; i <= num; i ++) {
if ((i & 1) == 1) {
ans[i] = ans[i - 1] + 1;
} else {
ans[i] = ans[i / 2];
}
}
return ans;
}
}
改进后
class Solution {
public int[] countBits(int num) {
int[] ans = new int[num + 1];
ans[0] = 0;
if (num == 0) return ans;
ans[1] = 1;
if ((num & 1) == 1) {
for (int i = 1; i < num; i += 2) {
ans[i] = ans[i - 1] + 1;
ans[i + 1] = ans[(i + 1)/ 2];
}
ans[num] = ans[num - 1] + 1;
} else {
for (int i = 2; i < num; i += 2) {
ans[i] = ans[i / 2];
ans[i + 1] = ans[i] + 1;
}
ans[num] = ans[num / 2];
}
return ans;
}
}