[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
        
相关推荐
GISHUB8 分钟前
基于QGIS 3.44开发Python插件完整教程
python·qgis
大数据魔法师21 分钟前
curl_cffi从入门到实战
爬虫·python
Sylvia33.24 分钟前
火星数据体育API|一站式接入足球篮球电竞等18+项目实时数据
java·开发语言·python·websocket·游戏
程序员清风43 分钟前
LangGraph 入门:用状态机设计可靠的 Agent 工作流
人工智能·python
Data_Journal1 小时前
使用 AutoScraper 进行网页抓取:分步教程
大数据·开发语言·数据库·python·scrapy
CodeRecycle1 小时前
Python 自动配置 pip 支持库(通过 Windows Bat 脚本)
算法
FanetheDivine1 小时前
学习python 1.搭建python环境
python
liliangcsdn1 小时前
特质偏度因子的计算示例和分析
算法
虎虎(_ _)。゜zzZ2 小时前
SQLAlchemy入门教程
数据库·后端·python·sql·ai·sqlalchemy
荆棘鸟智能2 小时前
无人机遥感图像实时拼接算法工程实践:从特征提取到全景融合的完整技术链路
算法·无人机