[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
        
相关推荐
m0_6403093021 分钟前
c++如何判断两个文件路径是否物理指向同一个磁盘文件_equivalent【详解】
jvm·数据库·python
数智工坊30 分钟前
深度拆解AnomalyAny:异常检测新工作,利用Stable Diffusion生成真实多样异常样本!
人工智能·pytorch·python·stable diffusion
Shorasul34 分钟前
Django 信号中为 ImageField 指定自定义保存路径的正确实践
jvm·数据库·python
Wyz2012102440 分钟前
CSS如何实现移动端点击高亮去除_设置tap-highlight-color
jvm·数据库·python
日光明媚42 分钟前
SoulX-FlashTalk 技术报告解读:从“严格因果”到“双向流式蒸馏”,实时数字人为什么能做到 0.87s 延迟、32FPS 和长时稳定?
人工智能·python·深度学习·ai作画·aigc·音视频
音视频牛哥44 分钟前
鸿蒙 NEXT RTSP/RTMP 播放器如何回调 RGB 数据并实现 AI 视觉算法分析
人工智能·算法·harmonyos·鸿蒙rtmp播放器·鸿蒙rtsp播放器·鸿蒙next rtsp播放器·鸿蒙next rtmp播放器
粉嘟小飞妹儿1 小时前
如何在云主机上安装Oracle 19c_公网IP绑定与安全组端口开放
jvm·数据库·python
飞Link1 小时前
掌控 Agent 的时空法则:LangGraph Checkpoint (检查点) 机制深度实战
开发语言·python·算法
zopple1 小时前
Laravel与ThinkPHP框架深度对比
java·python·php·laravel
乐迪信息1 小时前
智慧港口中AI防爆摄像机的船舶越线识别功能
大数据·人工智能·物联网·算法·目标跟踪