力扣——位运算

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
相关推荐
未知陨落3 小时前
LeetCode:83.打家劫舍
算法·leetcode
两只程序猿3 小时前
数据可视化 | Violin Plot小提琴图Python实现 数据分布密度可视化科研图表
开发语言·python·信息可视化
Pluchon3 小时前
硅基计划4.0 算法 字符串
java·数据结构·学习·算法
三年呀4 小时前
共识算法的深度探索:从原理到实践的全面指南
算法·区块链·共识算法·分布式系统·区块链技术·高性能优化
alex1004 小时前
BeaverTails数据集:大模型安全对齐的关键资源与实战应用
人工智能·算法·安全
麦格芬2304 小时前
LeetCode 416 分割等和子集
数据结构·算法
大模型真好玩4 小时前
架构大突破! DeepSeek-V3.2发布,五分钟速通DeepSeek-V3.2核心特性
人工智能·python·deepseek
玩转C语言和数据结构4 小时前
Jupyter Notebook下载安装使用教程(附安装包,图文并茂)
ide·python·jupyter·anaconda·jupyternotebook·anaconda下载·anaconda安装包
2401_841495645 小时前
【自然语言处理】Universal Transformer(UT)模型
人工智能·python·深度学习·算法·自然语言处理·transformer·ut