[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
        
相关推荐
gis收藏家几秒前
利用 SAM2 模型探测卫星图像中的农田边界
开发语言·python
YiSLWLL5 分钟前
Tauri2+Leptos开发桌面应用--绘制图形、制作GIF动画和mp4视频
python·rust·ffmpeg·音视频·matplotlib
数据馅8 分钟前
python自动生成pg数据库表对应的es索引
数据库·python·elasticsearch
编程、小哥哥23 分钟前
python操作mysql
android·python
Serendipity_Carl24 分钟前
爬虫基础之爬取某站视频
爬虫·python·pycharm
2401_8904167131 分钟前
Recaptcha2 图像怎么识别
人工智能·python·django
杰九36 分钟前
我的世界(Minecraft)计算器python源码
python·开源·游戏程序
ExRoc44 分钟前
蓝桥杯真题 - 填充 - 题解
c++·算法·蓝桥杯
Channing Lewis1 小时前
python如何使得pdf加水印后的大小尽可能小
开发语言·python·pdf
利刃大大1 小时前
【二叉树的深搜】二叉树剪枝
c++·算法·dfs·剪枝