[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
        
相关推荐
devilnumber2 小时前
Java 递归算法 详解 + 核心要点 + 实战运用 + 避坑指南
java·开发语言·算法
大貔貅喝啤酒2 小时前
Python Requests库教程
自动化测试·python·requests库
copyer_xyf3 小时前
LangChain 调用 LLM
后端·python·agent
copyer_xyf3 小时前
Prompt 组织管理
后端·python·agent
‎ദ്ദിᵔ.˛.ᵔ₎4 小时前
双指针、滑动窗口、前缀和、二分查找 算法
算法
shimly1234564 小时前
python3 uvicorn 是啥?
python
顾北顾4 小时前
多头注意力机制
人工智能·深度学习·算法
H178535090964 小时前
SolidWorks_基于草图的实体特征20_特征错误排查
算法·3d建模·solidworks
hujinyuan201604 小时前
2025年12月中国电子学会青少年机器人技术等级考试试卷(二级) 真题+答案
人工智能·算法·机器人
CTA量化套保5 小时前
期货量化程序 time.sleep 卡死:天勤单线程与 deadline 替代
python·区块链