[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
        
相关推荐
佳xuan2 分钟前
模型训练之爬取数据
开发语言·python
张二娃同学6 分钟前
第12篇_深度学习学习路线总结
人工智能·python·深度学习·神经网络·学习
zmzb010310 分钟前
Python课后习题训练记录Day122
开发语言·python
淡海水19 分钟前
ComfyUI全面掌握-知识点详解——基础示例:文生图与图生图实操(参数+案例)
大数据·人工智能·算法·comfyui
05候补工程师24 分钟前
【硬核干货】用“算法”思维袭英语新题型:集合逆清晰除与降维打击解题法
经验分享·笔记·考研·算法·学习方法
m0_7020365331 分钟前
如何从Oracle Java调用外部API_HTTP请求在数据库Java Source中的实现
jvm·数据库·python
Freak嵌入式32 分钟前
WIZnet-EVB-Pico2开始,用MicroPython玩转以太网开发
arm开发·人工智能·python·嵌入式硬件·机器人·嵌入式·micropython
刀法如飞33 分钟前
Palantir Ontology 数据结构分析,与ER/OOP/DDD有什么区别?
人工智能·算法·架构
白藏y33 分钟前
【数据结构】简单选择排序
数据结构·算法·排序算法