[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
        
相关推荐
Dxy12393102164 分钟前
Python 如何使用 XPath 定位元素:从入门到实战
python
何陋轩17 分钟前
【重磅】悟空来了:国产AI编程助手深度测评,能否吊打Copilot?
人工智能·算法·面试
weixin_4249993621 分钟前
mysql行级锁失效的原因排查_检查查询条件与执行计划
jvm·数据库·python
yaoxin52112323 分钟前
389. Java IO API - 获取文件名
java·开发语言·python
Polar__Star28 分钟前
uni-app怎么实现App端一键换肤 uni-app全局样式动态切换【实战】
jvm·数据库·python
用户83562907805135 分钟前
使用 Python 自动管理 PowerPoint 幻灯片分节的方法
后端·python
逸风尊者1 小时前
XGBoost模型工程使用
java·后端·算法
LUVK_1 小时前
第七章查找
数据结构·c++·考研·算法·408
khalil10201 小时前
代码随想录算法训练营Day-31贪心算法 | 56. 合并区间、738. 单调递增的数字、968. 监控二叉树
数据结构·c++·算法·leetcode·贪心算法·二叉树·递归
奇牙2 小时前
DeepSeek V4 Agent 开发实战:用 deepseek-v4-pro 搭建多步骤工作流(2026 完整代码)
python