刷题中巧用逻辑运算总结(不定期跟新)

    技术2022-07-31  65

    python一行代码经常return 和/或者 之前做过一道巧用逻辑运算的题。把它找出来

    剑指offer56-Ⅰ 数组中数字只出现一次,其他数字出现两次

    class Solution: def singleNumbers(self, nums: List[int]) -> List[int]: # 位运算:一个数异或他本身为0 a,b,res=0,0,0 for n in nums: res^=n h=1 while (res&h==0):# 找到第一个不为0的位 h <<= 1 for n in nums: if (n&h==0):# 通过该位为0或非0分为两组(这两个数一定在不同组) a^=n else: b^=n return [a,b]

    剑指offer56-Ⅱ 数组中数字只出现一次,其他数字出现三次

    class Solution: def singleNumber(self, nums: List[int]) -> int: count=[0]*32 for n in nums: for j in range(32): count[j]+=n&1 n >>= 1 res,m=0,3 for i in range(32): res <<= 1 res |= count[31-i]%m return res if count[31]%m==0 else ~(res^0xffffffff) 由于 Python 的存储负数的特殊性,需要先将 000 - 323232 位取反(即 res ^ 0xffffffff ),再将所有位取反(即 ~ )。 两个组合操作实质上是将数字 323232 以上位取反, 000 - 323232 位不变

    剑指offer65-不用四则运算做加法

    o(1) o(1)

    class Solution: def add(self, a: int, b: int) -> int: x = 0xffffffff a,b = a & x,b & # 32位以上取0 while b != 0: a,b = a ^ b,a & b << 1 & x return a if a <= 0x7fffffff else ~(a ^ x)# 若a为负数,则将他32位以上取1(负数补码原因) # 考虑Python存储数字均为补码,没有int ,long不同长度类型变量,无变量位数概念
    Processed: 0.009, SQL: 9