LeetCode - 按标签分类刷题(位运算题解)
目录
- XOR - 异或
- 判断奇偶:
- [51. n皇后](https://leetcode-cn.com/problems/n-queens/)
- [52. n皇后II](https://leetcode-cn.com/problems/n-queens-ii/description/)
- [190. 颠倒二进制位](https://leetcode-cn.com/problems/reverse-bits/)
- [191. 位1的个数](https://leetcode-cn.com/problems/number-of-1-bits/)
- [231. 2的幂](https://leetcode-cn.com/problems/power-of-two/)
- [338. 比特位计数](https://leetcode-cn.com/problems/counting-bits/description/)
XOR - 异或
异或:相同我0,不同为1 也可用“不进位加法”来理解。
异或操作的一些特点:
x ^ 0 = x
x ^ 1s = ~x //注意1s = ~ 0
x ^ (~x) = 1s
x ^ x = 0
c = a ^ b => a ^ c = b,b ^ c= a//交换两个数
a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c
判断奇偶:
x % 2 == 1 ——> (x & 1) == 1
x % 2 == 0 ——> (x & 1) == 0
x >> 1 ——> x / 2
即:x = x / 2 ; ——> x = x >> 1;
mid = (left + right)/2;——> mid = (left + right) >> 1;
x = x & (x - 1) 清零最低位的1
x & -x => 得到最低位的1
x &(~x)=> 0
51. n皇后
private int size;
private int count;
private void solve(int row,int ld, int rd){
if (row == size){
count++;
return;
}
int pos = size & (~(row | ld | rd));
while (pos != 0){
int p = pos &(~pos);
pos &= pos - 1;
solve(row | p,(ld | p) << 1,(rd | p) >> 1);
}
}
public int totalNQueens(int n){
count = 0;
size = (1 << n) - 1;
solve(0,0,0);
return count;
}
52. n皇后II
190. 颠倒二进制位
题解:
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int ans = 0;
for(int i = 0;i < 32;i++){
ans = (ans << 1) + (n & 1);
n >>= 1;
}
return ans;
}
}
191. 位1的个数
方法一: 循环32次,遍历找出1的个数
方法二: %2 /2
方法三: &1,x = x >> 1
方法四: while(x > 0) x = x & (x - 1); // 清零最低位的 1
循环和位移动
//方法三代码
public int hammingWeight(int n) {
int count = 0;
int mask = 1;
for (int i = 0; i < 32; i++) {
if ((n & mask) != 0){
count++;
}
mask <<= 1;
}
return count;
}
//方法四代码
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
count++;
n &= (n - 1);
}
return count;
}
}
231. 2的幂
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
while (n % 2 == 0) n /= 2;
return n == 1;
}
}
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
long x = (long) n;
return (x & (-x)) == x;
}
}
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
long x = (long) n;
return (x & (x - 1)) == 0;
}
}
DP + 位运算