[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
        
相关推荐
KaMeidebaby12 小时前
卡梅德生物技术快报|原核膜蛋白表达优化实操手册,膜蛋白的纯化梯度洗脱完整流程
前端·网络·数据库·人工智能·算法
naturerun12 小时前
逐步插入回路法构造欧拉回路的算法
c++·算法
qizayaoshuap12 小时前
# [特殊字符] 骰子模拟器 — 鸿蒙ArkTS随机算法与动画系统设计
算法·华为·harmonyos
humbinal12 小时前
同时支持 gui & cli 的 parquet 文件查看工具,高性能小清新!
hive·python·rust·spark·开源·github·parquet
90后的晨仔12 小时前
Python 开发完全指南:从入门到工程化落地
python
山顶夕景12 小时前
【DWT】计算两不等序列相似度:DWT
算法·动态规划·检索·模式识别·相似度
Mikowoo00713 小时前
批量汇总XML格式的发票信息
xml·python
胡耀超13 小时前
从一次批量爬取到生产同步:问题变了,建设边界也要跟着变
爬虫·python·系统架构·数据治理·数据同步·接口设计·爬虫工程
旅僧13 小时前
王树森老师强化学习--同声传译版3
python·深度学习
梦想不只是梦与想13 小时前
python中精度处理:decimal
python·float·精度丢失·decimal·浮点运算