[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
        
相关推荐
神明9315 分钟前
数据库模型设计实战:如何导出数据库完整数据字典_规范化流程
jvm·数据库·python
老纪6 分钟前
SQL中如何查找包含关键字的行:FULLTEXT全文索引检索
jvm·数据库·python
茉莉玫瑰花茶7 分钟前
LangGraph 入门教程:构建 AI 工作流 [ 案例二 ]
开发语言·人工智能·python
yaoxin5211237 分钟前
403. Java 文件操作基础 - 写入二进制文件
java·开发语言·python
dfdfadffa8 分钟前
c++怎么利用std--filesystem--path处理包含多个扩展名的文件名【详解】
jvm·数据库·python
宵时待雨10 分钟前
优选算法专题6:模拟
数据结构·c++·算法·leetcode·职场和发展
Liangwei Lin15 分钟前
LeetCode 35. 搜索插入位置
数据结构·算法·leetcode
数智工坊17 分钟前
【经典RL算法】Q-Learning:强化学习的里程碑——从理论到收敛证明的完整解析
论文阅读·人工智能·深度学习·算法·transformer
叼烟扛炮19 分钟前
C++ 知识点19 匿名对象
开发语言·c++·算法·匿名对象
阿正呀21 分钟前
c++如何动态追加JSON数组到已有文件_nlohmann局部修改【详解】
jvm·数据库·python