[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
        
相关推荐
宋均浩6 分钟前
AI 生成代码质量防线实战:5 个 CI/CD 配置,把 8% 的逻辑错拦在线上之前0
python
树码小子16 分钟前
Pycharm解释器配置问题解决
ide·python·pycharm
国雪24 分钟前
python-协程
python
乐观勇敢坚强的老彭27 分钟前
C++ 竞赛常用算法模板速查表
开发语言·c++·算法
高洁0132 分钟前
工信部教考中心证书
人工智能·深度学习·算法·机器学习·知识图谱
一木 之林35 分钟前
Python.六.(一)--1.标准库、常用工具与基础操作(进阶)
python·rpc·dubbo
我变成萤火虫1 小时前
河南萌新联赛2026第(三)场:郑州轻工业大学
数据结构·c++·算法·贪心算法·stl·深度优先·哈希算法
Dr.kangder1 小时前
嵌入式面试总结(十九)——内存泄露
单片机·算法·面试·职场和发展·架构·硬件架构
月光船幽幽1 小时前
铁牌协议卡:节流与重构
python·重构
Herbert_hwt1 小时前
【C语言基础】常量、选择结构与运算符全解析
c语言·开发语言·算法