[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
        
相关推荐
章鱼丸-5 分钟前
DAY31 文件的拆分和写法
开发语言·python
☆56614 分钟前
C++中的命令模式
开发语言·c++·算法
仰泳的熊猫16 分钟前
题目2577:蓝桥杯2020年第十一届省赛真题-走方格
数据结构·c++·算法·蓝桥杯
唐叔在学习17 分钟前
Python桌面端应用最小化托盘开发实践
后端·python·程序员
2501_9454235418 分钟前
使用Fabric自动化你的部署流程
jvm·数据库·python
2401_8463416520 分钟前
用Pandas处理时间序列数据(Time Series)
jvm·数据库·python
未知鱼30 分钟前
Python安全开发之子域名扫描器(含详细注释)
网络·python·安全·web安全·网络安全
2401_8318249633 分钟前
编写一个Python脚本自动下载壁纸
jvm·数据库·python
2401_8579182943 分钟前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
CoovallyAIHub1 小时前
Pipecat:构建实时语音 AI Agent 的开源编排框架,500ms 级端到端延迟
深度学习·算法·计算机视觉