[NeetCode 150] Reverse Bits

Reverse Bits

Given a 32-bit unsigned integer n, reverse the bits of the binary representation of n and return the result.

Example 1:

复制代码
Input: n = 00000000000000000000000000010101

Output:    2818572288 (10101000000000000000000000000000)

Explanation: Reversing 00000000000000000000000000010101, which represents the unsigned integer 21, gives us 10101000000000000000000000000000 which represents the unsigned integer 2818572288.

Solution

We can convert the number into a binary number and store its bits, then sum up the bits in reverse order.

Or actually we don't need to store the bits, as we've already known where the bit will be after reversion.

Code

Convert and store:

py 复制代码
class Solution:
    def reverseBits(self, n: int) -> int:
        bits = []
        while n > 0:
            bits.append(n%2)
            n //= 2
        
        while len(bits) < 32:
            bits.append(0)

        ans = 0
        for bit in bits:
            ans <<= 1
            ans += bit
        
        return ans
        

No store:

py 复制代码
class Solution:
    def reverseBits(self, n: int) -> int:
        ans = 0
        for i in range(32):
            bit = (n >> i) & 1
            ans += bit<<(31-i)
        return ans
        
相关推荐
是小蟹呀^12 分钟前
【总结】LangChain中工具的使用
python·langchain·agent·tool
宝贝儿好21 分钟前
【LLM】第二章:文本表示:词袋模型、小案例:基于文本的推荐系统(酒店推荐)
人工智能·python·深度学习·神经网络·自然语言处理·机器人·语音识别
王夏奇38 分钟前
pythonUI界面弹窗设置的几种办法
python·ui
ZhengEnCi1 小时前
P2B-Python可迭代对象完全指南-从列表到生成器的Python编程利器
python
不爱吃炸鸡柳1 小时前
单链表专题(完整代码版)
数据结构·算法·链表
CylMK1 小时前
题解:AT_abc382_d [ABC382D] Keep Distance
算法
Dfreedom.1 小时前
计算机视觉全景图
人工智能·算法·计算机视觉·图像算法
萌萌站起2 小时前
Vscode 中 python模块的导入问题
ide·vscode·python
是小蟹呀^2 小时前
【总结】提示词工程
python·llm·prompt·agent
YBAdvanceFu2 小时前
从零构建智能体:深入理解 ReAct Plan Solve Reflection 三大经典范式
人工智能·python·机器学习·数据挖掘·多智能体·智能体