[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
        
相关推荐
数字融合16 小时前
透明化视频驱动化工生产动态三维重建管控技术
大数据·人工智能·python
屿华AI17 小时前
AUTOSAR 实战-诊断工具 | DTC/Event/FiM 故障报告自动化:DEM 诊断数据采集与解析
python·测试工具·自动化·汽车
贝壳69017 小时前
9.13.12 那三个新功能,我一个一个跑了一遍:两个真香,一个有前提
python
2601_9679801117 小时前
Python 与云计算:AWS、GCP、Azure 实践
python·云计算·azure·aws·gcp
屿华AI17 小时前
AUTOSAR 实战-诊断工具 | 基于 Python 与 USB-CANFD 的 UDS 诊断测试工具设计与实现
开发语言·python·测试工具
贝壳69017 小时前
三家 AI 把我的实测数据判成造假,我在同一台机器上重跑了五组
python
用户0190275816117 小时前
Telegram Bot 股票到价提醒:AlphaFeed 轮询 + sendMessage
python
电科_银尘18 小时前
【大模型算法与工程 01】机器学习的问题定义:监督、无监督、自监督与强化学习
人工智能·算法·机器学习
电科_银尘18 小时前
【大模型算法与工程 05】分类、回归与排序指标:怎样评价一个模型
算法·分类·回归
黑客笔记18 小时前
Python 进程池和线程池:用等待任务理解并发
开发语言·python