力扣——位运算

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
相关推荐
2401_8384725117 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
CoLiuRs17 小时前
语义搜索系统原理与实现
redis·python·向量·es
zhihuaba17 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
u01092727117 小时前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python
智者知已应修善业18 小时前
【查找字符最大下标以*符号分割以**结束】2024-12-24
c语言·c++·经验分享·笔记·算法
91刘仁德18 小时前
c++类和对象(下)
c语言·jvm·c++·经验分享·笔记·算法
diediedei18 小时前
模板编译期类型检查
开发语言·c++·算法
Stream_Silver18 小时前
【Agent学习笔记3:使用Python开发简单MCP服务】
笔记·python
穿过锁扣的风18 小时前
零基础入门 Python 爬虫:从基础到实战,爬取虎扑 / 豆瓣 / 图片全掌握
开发语言·爬虫·python
阿杰学AI18 小时前
AI核心知识78——大语言模型之CLM(简洁且通俗易懂版)
人工智能·算法·ai·语言模型·rag·clm·语境化语言模型