[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
        
相关推荐
北斗落凡尘7 分钟前
LangGraph 入门实战(5)
python·langchain
乐观勇敢坚强的老彭8 分钟前
C++ STL 常用容器的速查表
java·c++·算法
北冥you鱼11 分钟前
深入解析 Go 中 sync.YAML.Unmarshal:如何将 YAML 数据填充到 Config 结构体
开发语言·算法·golang
Python私教17 分钟前
请求超时不等于失败:把写操作恢复设计成事实回读
后端·python
且听风吟022025 分钟前
7.包管理工具
python
程序员杰哥1 小时前
依赖于第三方接口时,如何进行测试?
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
java修仙传1 小时前
从网页禅道到 AI 能调用的工具:我的禅道 MCP 实现思路分享
java·人工智能·python·ai应用·mcp开发
reasonsummer1 小时前
【办公类-120-01】20260812闵行区幼儿园概况表的数据统计(户籍、五类性质、优抚子女)
前端·python
星轨初途1 小时前
LeetCode 热题 100——day11 滑动窗口最大值
数据结构·c++·算法·leetcode·职场和发展
梦想的旅途21 小时前
企业微信API实战:Python自动化消息推送
java·前端·python·自动化·企业微信