[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
        
相关推荐
迅猛龙办公室3 分钟前
Python实现PM空气质量提醒
服务器·前端·python
看浪的路人19 分钟前
第6讲:Agent 安全体系——Prompt 注入防御、工具调用审计与输出合规
人工智能·算法
小马不起床25 分钟前
Django 后端实战指南_9:前后端完整联调和问题修复
python·django·状态模式
局部有解29 分钟前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
垆边人似月.39 分钟前
移动长度 k 子串使字符串变成回文
数据结构·算法
pride.li1 小时前
第12章 Python 教程-流程控制:循环结构
linux·服务器·python·算法
鬼手点金1 小时前
模型即 Agent:当模型本身成为产品
开发语言·前端·人工智能·python·机器学习
田里的水稻1 小时前
PyTorch-Dataset\DataLoader数据加载
人工智能·pytorch·python
海绵宝宝转agent1 小时前
2026-10-16 4算法+1面经
算法
卷无止境1 小时前
Python 3.14 自由线程:拆掉 GIL 之后,我们到底得到了什么
后端·python