[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
        
相关推荐
初生牛犊不怕苦1 分钟前
与AI一起学习《C专家编程》:数组与指针
c语言·学习·算法
华科大胡子15 分钟前
Chrome安全机制深度解析
python
易标AI21 分钟前
标书智能体(四)——提示词顺序优化,让缓存命中,输入成本直降10倍
人工智能·python·提示词·智能体·招投标
Kk.080225 分钟前
数据结构|排序算法(二) 冒泡排序
数据结构·算法·排序算法
深耕AI25 分钟前
【VS Code 中 Python 虚拟环境降级完整指南(含 uv 工具实战)】
开发语言·python·uv
沛沛rh4529 分钟前
深入并发编程:从 C++ 到 Rust 的学习笔记
c++·笔记·学习·算法·rust
→长歌1 小时前
2026Java面试30题精解
java·python·面试
Bert.Cai1 小时前
pymysql自动提交设置
开发语言·python
吃一根烤肠1 小时前
Python调试革命:用ChatGPT Copilot快速定位复杂bug
python·chatgpt·copilot
Kk.08021 小时前
数据结构|排序算法(二) 希尔排序
数据结构·算法·排序算法