前言
###我做这类文档一个重要的目的还是给正在学习的大家提供方向(例如想要掌握基础用法,该刷哪些题?)我的解析也不会做的非常详细,只会提供思路和一些关键点,力扣上的大佬们的题解质量是非常非常高滴!!!
习题
1.2的幂
题目链接:231. 2 的幂 - 力扣(LeetCode)
题面:
代码:
java">class Solution {public boolean isPowerOfTwo(int n) {if(n<=0)return false;return ((n&(-n))==n?true:false);}
}
2.4的幂
题目链接:342. 4的幂 - 力扣(LeetCode)
题面:
代码:
java">class Solution {public boolean isPowerOfFour(int n) {if(n<=0)return false;if(((-n)&n)!=n)return false;int len = (int)(Math.log(n)/Math.log(2))+1;return ((len-1)%2==0);}
}
3.位1的个数
题目链接:191. 位1的个数 - 力扣(LeetCode)
题面:
代码:
java">class Solution {public int hammingWeight(int n) {int ans = 0;for(int i = n;i>0;i-=lowbit(i))ans++;return ans;}public int lowbit(int n){return (-n)&n;}
}
4.奇偶位数
题目链接:2595. 奇偶位数 - 力扣(LeetCode)
题面:
代码:
java">class Solution {public int[] evenOddBit(int n) {int[] ans = new int[2];int flag;for(int i = n;i>0;i-=flag){flag = lowbit(i);int len = (int)(Math.log(flag)/Math.log(2))+1;ans[(len-1)%2]++;} return ans;}public int lowbit(int n){return (-n)&n;}
}
5. 比特位计数
题目链接:338. 比特位计数 - 力扣(LeetCode)
题面:
代码:
java">class Solution {public int[] countBits(int n) {int[] ans = new int[n+1];for(int i = 0;i<=n;i++){ans[i]=Integer.bitCount(i);}return ans;}}
6.数组异或操作
题目链接:1486. 数组异或操作 - 力扣(LeetCode)
题面:
代码:
java">class Solution {public int xorOperation(int n, int start) {int[] arr = new int[n];int sum = start+2*0;for (int i = 1; i < n; i++) {sum=sum^(start+i*2);}return sum;}
}
7.解码异或后的数组
题目链接:1720. 解码异或后的数组 - 力扣(LeetCode)
题面:
代码:
java">class Solution {public int[] decode(int[] encoded, int first) {int n = encoded.length;int[] ans = new int[n+1];ans[0] = first;for(int i = 0;i<n;i++){ans[i+1] = first^encoded[i];first = ans[i+1];}return ans;}
}
8.找出前缀异或的原始数组
题目链接:2433. 找出前缀异或的原始数组 - 力扣(LeetCode)
题面:
代码:
java">class Solution {public int[] findArray(int[] pref) {int n = pref.length;int flag = pref[0];for(int i = 1;i<n;i++){pref[i] = pref[i]^flag;flag^=pref[i];}return pref;}
}
9.子数组异或查询
题目链接:1310. 子数组异或查询 - 力扣(LeetCode)
题面:
代码:
java">class Solution {public int[] xorQueries(int[] arr, int[][] queries) {int n = arr.length;for(int i = 1;i<n;i++){arr[i] = arr[i]^arr[i-1];}n = queries.length;int[] ans = new int[n];for(int i = 0;i<n;i++){if(queries[i][0]==0){ans[i] = arr[queries[i][1]];}else{ans[i] = arr[queries[i][1]]^arr[queries[i][0]-1];}}return ans;}
}
10.相邻值的安慰异或
题目链接:2683. 相邻值的按位异或 - 力扣(LeetCode)
题面:
代码:
java">class Solution {public boolean doesValidArrayExist(int[] derived) {int n = derived.length;int ans = derived[0];for(int i = 1;i<n;i++){ans^=derived[i];}return ans==0;}
}
后言
上面是力扣位运算专题,下一篇是其他的习题,希望有所帮助,一同进步,共勉!