力扣——位运算

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
相关推荐
I疯子4 分钟前
2026-04-08 打卡第 5 天
开发语言·windows·python
wfbcg8 分钟前
每日算法练习:LeetCode 15. 三数之和 ✅
算法·leetcode·职场和发展
2301_8227032014 分钟前
开源鸿蒙跨平台Flutter开发:跨端图形渲染引擎的类型边界与命名空间陷阱:以多维雷达图绘制中的 dart:ui 及 StrokeJoin 异常为例
算法·flutter·ui·开源·图形渲染·harmonyos·鸿蒙
y = xⁿ15 分钟前
【LeetCode Hot100】双指针:分离指针
算法·leetcode
学习永无止境@16 分钟前
Verilog中有符号数计算
图像处理·算法·fpga开发
C+++Python18 分钟前
Python MCP Server 最简实现
开发语言·python
6Hzlia20 分钟前
【Hot 100 刷题计划】 LeetCode 41. 缺失的第一个正数 | C++ 原地哈希题解
c++·leetcode·哈希算法
zhuhezhang26 分钟前
一个用python开发的文本对比工具
python·文本对比工具
智算菩萨27 分钟前
【Python图像处理】5 Pillow图像处理与格式转换
图像处理·python·pillow
人工干智能36 分钟前
科普:%%matplotlib inline:魔法命令 (Cell Magic)
python·matplotlib