[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
        
相关推荐
badhope3 分钟前
2025年3月AI领域纪录:从模型开源到智能体价值重估——风云变幻DLC
人工智能·python·深度学习·计算机视觉·数据挖掘
XiYang-DING5 分钟前
【LeetCode】118.杨辉三角
算法·leetcode·职场和发展
小陈工11 分钟前
Python Web开发入门(一):虚拟环境与依赖管理,从零搭建纯净开发环境
开发语言·前端·数据库·git·python·docker·开源
wuhen_n12 分钟前
排列算法完全指南 - 从全排列到N皇后,一套模板搞定所有排列问题
前端·javascript·算法
ai生成式引擎优化技术16 分钟前
拓世网络技术开发工作室的ts概率递推ai工程应用技术GEOChatGPT,不同用户账号信息,网站引用效果
算法
七夜zippoe17 分钟前
联邦学习实战:隐私保护的分布式机器学习——联邦平均与差分隐私
分布式·python·机器学习·差分隐私·联邦平均
CylMK17 分钟前
题解:UVA1218 完美的服务 Perfect Service
数据结构·c++·算法·深度优先·图论
重生之我是Java开发战士19 分钟前
【广度优先搜索】BFS解决拓扑排序:课程表I,课程表II,火星词典
算法·leetcode·广度优先
不懒不懒23 分钟前
【OpenCV 计算机视觉四大核心实战:从背景建模到目标跟踪】
人工智能·python·opencv·机器学习·计算机视觉
coderlin_25 分钟前
Django DRF开发
python·django·sqlite