(刷题笔记)位运算
1、n & (n-1)
n & (n-1)
作用是消除数字 n
的二进制表示中的最后一个 1
191. 位1的个数 - 力扣(LeetCode) (leetcode-cn.com)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
while(n!=0){
n = n & (n - 1);
res++;
}
return res;
}
}
231. 2 的幂 - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
public boolean isPowerOfTwo(int n) {
if(n <= 0)
return false;
return (n&(n-1)) == 0;
}
}
762. 二进制表示中质数个计算置位 - 力扣(LeetCode) (leetcode-cn.com)
由于整数最多能由32位二进制数表示,可以先对这32个数打表
class Solution {
static boolean[] hash = new boolean[32];
{
int[] nums = {2,3,5,7,11,13,17,19,23,29,31};
for(int num : nums)
hash[num] = true;
}
public int countPrimeSetBits(int left, int right) {
int cnt = 0;
for(int i = left; i <= right; i++){
int cur = i;
int curOne = 0;
while(cur > 0){
cur = cur & (cur - 1);
curOne++;
}
if(hash[curOne] == true)
cnt++;
}
return cnt;
}
}
2、a ^ a = 0
一个数和它本身做异或运算结果为 0,即 a ^ a = 0
;一个数和 0 做异或运算的结果为它本身,即 a ^ 0 = a
。
136. 只出现一次的数字 - 力扣(LeetCode) (leetcode-cn.com)
只要把所有数字进行异或,成对儿的数字就会变成 0,落单的数字和 0 做异或还是它本身,所以最后异或的结果就是只出现一次的元素:
class Solution {
public int singleNumber(int[] nums) {
int res = nums[0];
for(int i = 1 ; i < nums.length ; i++)
res = res ^ nums[i];
return res;
}
}
268. 丢失的数字 - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
int missingNumber(int[] nums) {
int n = nums.length;
int res = 0;
// 先和新补的索引异或一下
res ^= n;
// 和其他的元素、索引做异或
for (int i = 0; i < n; i++)
res ^= i ^ nums[i];
return res;
}
}