[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
        
相关推荐
ss.li3 小时前
rppg阅读笔记 2026.10.15
图像处理·python·计算机视觉
大貔貅喝啤酒3 小时前
Unittest框架使用教程
自动化测试·python
信奥卷王3 小时前
[GESP202503 六级] 环线(含视频)
算法
一个简单的TTS开发者4 小时前
中文TTS工具有哪些-8款主流方案横向对比
人工智能·后端·python·indextts
CQU_JIAKE4 小时前
10.15【A】
算法
yunfanleo4 小时前
temperature 详解:大模型采样参数原理、三种用法与工程实践
人工智能·python·rpa
晴天的雨.9924 小时前
【C++】模板进阶
开发语言·c++·算法
木井巳4 小时前
【动态规划】三步问题
java·算法·leetcode·动态规划·推荐算法
CarIise4 小时前
Maven依赖传递与聚合工程
python·r语言·django
楚识科技4 小时前
手写 OCR 识别技术深度解析:从算法原理到政企级落地实现
算法·ocr