(LeetCode)位运算

0. 总结

位运算常见的操作:异或统计二进制中1的个数

1. 汉明距离

461. hamming-distance
在这里插入图片描述

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int

        思路
            先异或, 再使用bin函数统计1的个数
            bin(xor).count('1')

            先异或, 再通过xor与xor-1取&, 计算1的位数
        """
        xor = x ^ y
        dist = 0
        while xor:
            dist += 1
            xor = xor & (xor - 1)
        return dist

2. 只出现一次的数字

136. single-number
在这里插入图片描述

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int

        笨办法:
        1. 使用Counter
            [val for val, freq in Counter(nums).items() if freq == 1][0]
        2. 先排序,再左右邻居跟自己不等,就输出;

        聪明解法:
        异或运算,对整个数组异或,相同元素抵消,只留下频次为1的一个元素
        https://leetcode-cn.com/problems/single-number/comments/42235
        """
        r = 0
        for num in nums:
            r = r ^ num
        return r

3. 比特位计数

338. counting-bits
在这里插入图片描述

class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        思路
            计算一个整数的二进制形式的1的位数 我们在海明距离题目中已经实现过
            这里不过是在上面封装了一个数组
        """
        def count_one(x):
            cnt = 0
            while x:
                cnt += 1
                x = x & (x - 1)
            return cnt
        
        result = [count_one(i) for i in range(num+1)]
        # result = [bin(i).count('1') for i in range(num+1)]  # 使用内置bin函数
        return result
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值