[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
        
相关推荐
ServBay3 小时前
9 个 Python 第三方库推荐,不用 AI 都好像多出一个团队
后端·python
用户8356290780513 小时前
如何使用 Python 添加和管理 Excel 批注(完整示例)
后端·python
用户8356290780513 小时前
使用 Python 管理 Excel 工作表:创建、复制、删除与重命名
后端·python
05Kevin11 小时前
lk每日冒险题--数据结构6.27
算法
荣码12 小时前
LangGraph多Agent协作:3个Agent干活比1个强,但我踩了4个坑
java·python
To_OC1 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安1 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
用户8356290780511 天前
Python 操作 PDF 附件:添加、查看与管理指南
后端·python