(刷题笔记)位运算

(刷题笔记)位运算

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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值