[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
        
相关推荐
满怀冰雪10 小时前
03-第一个 Paddle 程序:Tensor 创建、计算与设备管理
人工智能·python·paddle
QXWZ_IA10 小时前
1库1图1批是什么?千寻位置公安地图数据体系详解
科技·算法·能源·媒体·交通物流·政务
CClaris11 小时前
大模型量化从0到1(九):用 llama.cpp 把模型转成 GGUF 并跑本地推理
人工智能·pytorch·python·深度学习·llama
学编程的小虎11 小时前
SenseVoice微调
人工智能·python·自然语言处理
c2385611 小时前
Bug 猎手入门指南
c++·算法·bug
诸葛说抛光11 小时前
国内大型汽车改装展览会定展 佛山改装 佛山汽车赛事
python·汽车
chouchuang11 小时前
day-030-综合练习-笔记管理器
开发语言·笔记·python
乖巧的妹子11 小时前
Python基础核心知识点详解:内置函数、运算符、字符串方法、数据结构与类型转换
python
Reart11 小时前
Leetcode 213.打家劫舍2(内含闲谈,打劫真是技术活,好题,716)
后端·算法
幸福清风12 小时前
Python 完美处理Excel合并单元格:拆分填充+自动合并
python·excel·合并单元格·拆分单元格