力扣——位运算

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
相关推荐
biter down2 小时前
从 0 到 1 搭建 Python 接口自动化测试框架(博客系统实战)
开发语言·python
小欣加油2 小时前
leetcode56 合并区间
c++·算法·leetcode·职场和发展
lqqjuly2 小时前
前沿算法深度解析(二)
人工智能·算法·机器学习
肖永威4 小时前
Python多业务并行计算框架插件化演进:从硬编码到动态注册
python·插件化·并行计算·动态注册
yz_aiks4 小时前
Linux Jar包配置Systemd自启动实战:从排查到配置全流程
linux·python·jar·自启动·systemd
徐小夕4 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
不知名的老吴4 小时前
线程的生命周期之线程“插队“
java·开发语言·python
akunkuntaimei4 小时前
2026年高考数学各省真题及答案(完整版)
算法·高考
Hello:CodeWorld5 小时前
C 风格变参 vs C++ 变参模板:核心区别与选型指南
c语言·c++·算法
xsc6996755 小时前
从零搭建大模型与智能体平台 - 完整技术详解
python