[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
        
相关推荐
0566467 小时前
agent学习Day15——SQLAlchemy 查询过滤、分页与历史列表接口
python·学习·fastapi
程序员爱德华8 小时前
Python与C++:异同点对比
c++·python
hangyuekejiGEO8 小时前
GEO技术服务选型指南
大数据·人工智能·python
普通攻击往后拉8 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
软萌萌的19 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
@syh.9 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
可编程芯片开发10 小时前
基于零极点配置的PID控制系统simulink建模与仿真
算法
Dxy123931021610 小时前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
徐小夕10 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github