https://www.cnblogs.com/findbetterme/p/10787118.html
看这个就完事了
1. 统计两个数的二进制表示有多少位不同
461. Hamming Distance (Easy)
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
class Solution {
public int hammingDistance(int x, int y) {
int z=x^y;
int cnt=0;
while(z!=0){
if((z&1)==1)cnt++;
z=z>>1;
}
return cnt;
}
}
2. 数组中唯一一个不重复的元素
136. Single Number (Easy)
Input: [4,1,2,1,2]
Output: 4
class Solution {
public int singleNumber(int[] nums) {
int res=0;
for(int n:nums){
res=res^n;
}
return res;
}
}
3. 找出数组中缺失的那个数
268. Missing Number (Easy)
Input: [3,0,1]
Output: 2
class Solution {
public int missingNumber(int[] nums) {
int res=0;
for(int i=0;i<nums.length;i++){
res=res^nums[i]^i;
}
return res^nums.length;
}
}
4. 数组中不重复的两个元素
260. Single Number III (Medium)
两个不相等的元素在位级表示上必定会有一位存在不同。
将数组的所有元素异或得到的结果为不存在重复的两个元素异或的结果。
diff &= -diff 得到出 diff 最右侧不为 0 的位,也就是不存在重复的两个元素在位级表示上最右侧不同的那一位,利用这一位就可以将两个元素区分开来。
class Solution {
public int[] singleNumber(int[] nums) {
int diff=0;
for(int num:nums)diff^=num;
diff&=-diff; //得到最右一位
int[] ret=new int[2];
for(int num;nums){
if(num&diff)==0)ret[0]^=num;
else ret[1]^=num;
}
return ret;
}
}
5. 翻转一个数的比特位
190. Reverse Bits (Easy)
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res=0;
for(int i=0;i<32;i++){
res=(res<<1)+(n&1);
n>>=1;
}
return res;
}
}
7. 判断一个数是不是 2 的 n 次方
231. Power of Two (Easy)
二进制表示只有一个 1 存在。
class Solution {
public boolean isPowerOfTwo(int n) {
if(n<0)return false;
int cnt=0;
while(n!=0){
if((n&1)==1)cnt++;
n=n>>1;
}
return cnt==1;
}
}
8. 判断一个数是不是 4 的 n 次方
342. Power of Four (Easy)
class Solution {
public boolean isPowerOfFour(int n) {
if(n==0)return false;
while(n%4==0)n/=4;
return n==1;
}
}
9. 判断一个数的位级表示是否不会出现连续的 0 和 1
693. Binary Number with Alternating Bits (Easy)
class Solution {
public boolean hasAlternatingBits(int n) {
int a=(n^(n>>1));
return (a&(a+1))==0;
}
}