Leedcode算法专题训练(位运算)

https://www.cnblogs.com/findbetterme/p/10787118.html

看这个就完事了

1. 统计两个数的二进制表示有多少位不同

461. Hamming Distance (Easy)

Leetcode / 力扣

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)

Leetcode / 力扣

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)

Leetcode / 力扣

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)

Leetcode / 力扣

两个不相等的元素在位级表示上必定会有一位存在不同。

将数组的所有元素异或得到的结果为不存在重复的两个元素异或的结果。

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)

Leetcode / 力扣

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)

Leetcode / 力扣

二进制表示只有一个 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)

Leetcode / 力扣

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)

Leetcode / 力扣

class Solution {
    public boolean hasAlternatingBits(int n) {
        int a=(n^(n>>1));
        return (a&(a+1))==0;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值