[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
        
相关推荐
汤姆yu28 分钟前
基于python大数据的小说数据可视化及预测系统
大数据·python·信息可视化
x***J34832 分钟前
Python多线程爬虫
开发语言·爬虫·python
m***D28638 分钟前
Python网络爬虫实战案例
开发语言·爬虫·python
甄心爱学习43 分钟前
数据挖掘-聚类方法
人工智能·算法·机器学习
ID_180079054731 小时前
基于 Python 的淘宝商品详情数据结构化解析:SKU、价格与库存字段提取
开发语言·数据结构·python
星释1 小时前
Rust 练习册 82:Hamming与字符串处理
开发语言·算法·rust
Laughtin1 小时前
终端Python环境的选择与切换
开发语言·python
JHC0000002 小时前
Python PDF 相关操作
开发语言·python·pdf
databook2 小时前
Manim进阶:用背景图片让你的数学视频脱颖而出
python·动效
小张成长计划..2 小时前
【C++】16:模板进阶
c++·算法