leetcode --位运算基础知识以及应用

1. 位运算基础

按位运算符是把数字看作二进制来进行计算的。

1.1 基本表达

a与b: a&b
a或b: a|b
a异或b: a^b
非a: ~a
左移: <<
右移:>>

在这里插入图片描述

1.2 进制转换

二进制转十进制

>>> int('1101',2)  
13
>>> int('0o226',8)   #00226 0:阿拉伯数字零   o:小写英文字母 o    226:八进制数
150
>>> int('0x96',16)
150

十进制转二进制

>>> bin(13)
'0b1101'

八进制与十六进制互转

>>> oct(0x37)
'0o67'
>>> hex(0o67)
'0x37'

2. 题目

2.1 5649. 解码异或后的数组

这个题目考查异或相关的知识

a^b=c 能推出
c^b =a

在这里插入图片描述

class Solution:
    def decode(self, encoded: List[int], first: int) -> List[int]:
        res = [first]
        for i in range(len(encoded)):
            temp = first^encoded[i]    
            res.append(temp)
            first = temp
        return res   

2.2 5642. 大餐计数

在这里插入图片描述

这个题目有两个个重要的信息:

  1. 0 < = d e l i c i o u s n e s s [ i ] < = 2 20 0<=deliciousness[i]<=2^{20} 0<=deliciousness[i]<=220 ;也就是两个大餐之和最多为 2 21 2^{21} 221
  2. 1 < < i 1<<i 1<<i 表示 2 i 2^i 2i
    解法
    将问题转为,两数之和,target为 2 n 2^n 2n, 其中 1 < n < = 21 1<n<=21 1<n<=21
import collections
class Solution:
    def countPairs(self, deliciousness: List[int]) -> int:
        count = 0
        mod = 10**9+7
        for i in range(22):
            temp = 1<<i
            dicta = collections.defaultdict(lambda:0)
            for i, num in enumerate(deliciousness):
                if temp - num in dicta:
                    count +=dicta[temp - num]%mod
                dicta [num] += 1    
        return count%mod   

3. 参考链接:

https://www.cnblogs.com/gkx0731/p/9501276.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值