[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
        
相关推荐
Dmz丶13 小时前
前端转 AI 100 天 Day 42:跨模型对比实战——用数据选模型,不靠“听说”
python
路溪非溪13 小时前
python标准库使用总结
开发语言·python
青少儿编程课堂13 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:折半搜索优化子集枚举(Meet in the Middle)解析
c++·python·算法·bfs·信息学竞赛
用户9562562542914 小时前
五分钟用 E2B SDK 打通沙箱:环境变量只改三行
python·api
用户951794225102914 小时前
最小循环:让 Agent 跑起来(I1)
python·agent
沉默小管14 小时前
上班鼓励器_桌宠版
python
SomeOtherTime14 小时前
Rust 面向对象介绍(AI回答)
开发语言·python·rust
duansamve14 小时前
Flask中视图函数接收请求数据和返回响应实例
python·flask
Oneshot15 小时前
DLX(Dancing Links)算法详解:求解数独最快的算法
算法
用户2986985301415 小时前
用 Python 自动化把 JavaScript 代码转换为 Word 文档
javascript·python·api