力扣——位运算

python 复制代码
class Solution:
    def smallestNumber(self, n: int) -> int:
        return (1 << n.bit_length()) - 1
        
python 复制代码
class Solution:
    def minChanges(self, n: int, k: int) -> int:
        return -1 if n & k != k else (n ^ k).bit_count()
        
python 复制代码
class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        return sorted(arr, key=lambda x: (x.bit_count(), x))
python 复制代码
class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        return bin(x ^ y).count('1')
        
python 复制代码
class Solution:
    def minBitFlips(self, start: int, goal: int) -> int:
        # return bin(start ^ goal) .count('1')
        return (start ^ goal).bit_count()
        
python 复制代码
class Solution:
    def numberOfSteps(self, num: int) -> int:
        return num.bit_length() + num.bit_count() - 1 if num else 0
        
python 复制代码
class Solution:
    def findComplement(self, num: int) -> int:
        return num ^ ((1 << num.bit_length()) - 1)
        
python 复制代码
class Solution:
    def bitwiseComplement(self, n: int) -> int:
        Nbit = bin(n)
        return 2**len(Nbit[2:]) - 1 - n
        
python 复制代码
idx_map = {1<<i:i for i in range(30)}
class Solution:
    def binaryGap(self, n: int) -> int:
        def lowbit(x):
            return x & (-x)

        last, ans = inf, 0
        while n:
            n -= (cur := lowbit(n))
            ans, last = max(ans, idx_map[cur] - last), idx_map[cur]
        return ans        
python 复制代码
class Solution:
    def hasAlternatingBits(self, n: int) -> bool:
        return not (a := n ^ (n >> 1)) & (a + 1)
        
python 复制代码
class Solution:
    def xorOperation(self, n: int, start: int) -> int:
        xor_n = lambda n: (n, 1, n + 1, 0)[n % 4]
        a = start // 2
        b = n & start & 1  
        return (xor_n(a + n - 1) ^ xor_n(a - 1)) * 2 + b
相关推荐
San303 分钟前
从零到一:彻底搞定面试高频算法——“列表转树”与“爬楼梯”全解析
javascript·算法·面试
F_D_Z9 分钟前
最长连续序列(Longest Consecutive Sequence)
数据结构·算法·leetcode
ss2739 分钟前
Java并发编程:DelayQueue延迟订单系统
java·python·算法
JHC00000012 分钟前
118. 杨辉三角
python·算法·面试
@游子16 分钟前
Python类属性与魔术方法全解析
开发语言·python
WolfGang00732127 分钟前
代码随想录算法训练营Day50 | 拓扑排序、dijkstra(朴素版)
数据结构·算法
yuhaiqun198937 分钟前
Typora 技能进阶:从会写 Markdown 到玩转配置 + 插件高效学习笔记
经验分享·笔记·python·学习·学习方法·ai编程·markdown
业精于勤的牙40 分钟前
浅谈:算法中的斐波那契数(四)
算法
一直都在57244 分钟前
数据结构入门:二叉排序树的删除算法
数据结构·算法
白云千载尽1 小时前
ego_planner算法的仿真环境(主要是ros)-算法的解耦实现.
算法·无人机·规划算法·后端优化·ego·ego_planner