[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
        
相关推荐
abcy071213几秒前
python flask app.py里的接口放在别的目录下图文教程
python
弹简特6 分钟前
【零基础学Python】08-Python面向对象之封装、多态和函数进阶
开发语言·python
罗超驿9 分钟前
15.LeetCode 30. 串联所有单词的子串(Java):滑动窗口+哈希表详解
算法·leetcode
Marianne Qiqi9 分钟前
非hot100的力扣算法题
数据结构·算法·leetcode
专注VB编程开发20年20 分钟前
工控上位机开发为什么固死.net 4.5.2sdk?适配win7
python·信息可视化·c#
CC数学建模25 分钟前
2026第八届中青杯全国大学生数学建模竞赛C题:情绪维度耦合约束的脑电信号情绪识别 (1)完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
Dillon Dong27 分钟前
【风电控制】双馈风机网侧高低穿控制策略——从VrtCal信号处理到状态机逻辑的完整解析
算法·变流器·风电控制·dfig
下午写HelloWorld27 分钟前
同态加密(Homomorphic Encryption, HE)
人工智能·算法·密码学·同态加密
Kobebryant-Manba27 分钟前
安装cuda
pytorch·python·深度学习·conda·numpy
小何code28 分钟前
【Python零基础入门】第10篇:Python列表方法与应用实例
数据库·人工智能·python