[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
        
相关推荐
茉莉玫瑰花茶几秒前
LangGraph 拓展核心知识点
开发语言·windows·python
iAm_Ike1 分钟前
PHP错误和异常如何处理_PHP错误与异常处理机制详解【详解】
jvm·数据库·python
m0_631529826 分钟前
宝塔面板安装后无法修改配置文件_处理chattr锁定属性
jvm·数据库·python
坐吃山猪8 分钟前
【Hanako】README08_LEVEL4_插件系统架构
python·架构·agent·源码阅读
dFObBIMmai11 分钟前
Go语言怎么用GitHub Actions_Go语言GitHub Actions教程【基础】
jvm·数据库·python
老鱼说AI12 分钟前
现代 LangChain 开发指南:从 LCEL 原理到企业级 RAG 与 Agent 实战
java·开发语言·人工智能·深度学习·神经网络·算法·机器学习
Michelle802313 分钟前
25大数据 11-1 函数
开发语言·python
dFObBIMmai20 分钟前
SQL复杂数据聚合_嵌套子查询与GROUP BY配合
jvm·数据库·python
小许同学记录成长32 分钟前
基于幅度形态与参数聚类的工作模式判别
python·算法·scikit-learn
dinglu1030DL37 分钟前
CSS Grid布局如何实现网格项目排序_使用order属性改变显示顺序
jvm·数据库·python