[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
        
相关推荐
Sam09271 分钟前
【AI 算法精讲 13】朴素贝叶斯:文本分类的基石
人工智能·python·算法·ai
SilentSamsara5 分钟前
模型可解释性业务化:SHAP/LIME 的业务汇报与合规审查
人工智能·算法·机器学习·自动化
ai生成式引擎优化技术5 分钟前
WSaiOS:面向认知资产与工程化认知流程的智能操作系统架构
python·架构·django·virtualenv·pygame
STLearner7 分钟前
ICML 2026 | 时间序列(Time Series)论文总结【基础模型,生成,分类,异常检测,插补,表示学习和分析等】
论文阅读·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
byte轻骑兵11 分钟前
【LE Audio】CSIP精讲[5]: 蓝牙协同设备组的安全防护体系与实战规范
算法·安全·音频·le audio·低功耗音频
剑挑星河月13 分钟前
35.搜索插入位置
java·数据结构·算法·leetcode
冰暮流星14 分钟前
python之flask框架讲解-准备
开发语言·python·flask
闪电悠米24 分钟前
力扣hot100-438.找到字符串中所有字母异位词-固定长度滑动窗口详解
linux·服务器·数据结构·算法·leetcode·滑动窗口·力扣hot100
人道领域31 分钟前
【LeetCode刷题日记】51.N皇后
数据结构·算法
2501_947575808 小时前
计算机毕业设计之jsp开山车行二手车交易系统
java·开发语言·hadoop·python·信息可视化·django·课程设计