[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
        
相关推荐
沧海一笑-dj5 分钟前
【Python】Python学习笔记-初识 Python
python·python安装·python解释器
打工仔折腾 AI9 分钟前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn
hetao173383711 分钟前
2026-09-17 hetao1733837 的刷题记录
c++·算法
hanchenxing23 分钟前
AI 数据管道重构:从函数堆到链式管道的可读性实践
python
hhzz29 分钟前
【OpenCV 入门到精通 10】视频分析与光流跟踪:背景减除与运动检测
人工智能·python·opencv·性能优化
蓝胖的四次元口袋29 分钟前
Python基础语法入门
python
Patrick在香港1 小时前
Python 抓 0.91 GB 香港法例:Agent 的进度该写进磁盘,不是写进上下文
爬虫·python·api·claude·香港
午彦琳1 小时前
2026.9.17
数据结构·算法·leetcode
ClinicTech1 小时前
实验室洗瓶机的清洗系统架构与自动化控制解析
java·python
洋洋不叫杨杨1 小时前
Codex 实战:用 AI 写运维脚本
大数据·python