[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
        
相关推荐
YEGE学AI算法7 小时前
Python实现Log-Mel Fbank:分帧、加窗、FFT与Mel滤波器组
python·语音识别·fbank·log-mel·音频特征
甜到心里的蛋糕7 小时前
Playwright 无头浏览器自动发布 CSDN 图文草稿的实践(持久化 profile + 图床直传)
运维·python·playwright·爬虫自动化·博客运营
垆边人似月.8 小时前
华为OD算法题:查找众数及中位数
数据结构·算法·leetcode
hetao17338378 小时前
2026-10-08 hetao1733837 的刷题记录
c++·算法
jason.zeng@15022078 小时前
(六)Prompt 优化
python·ai·langchain·prompt·ai编程·llama
CoderYanger8 小时前
一轮复习——F.动态规划模型总结(入门篇)
java·开发语言·数据结构·算法·leetcode·职场和发展·动态规划
全栈练习生8 小时前
大模型推理全链路
python·ai
泡海椒9 小时前
JQuick-Excel VALIDATION 实战:用作用范围约束 Excel 导入校验
开发语言·python·excel
浅念-9 小时前
动态规划专题:斐波那契数列模型 + 网格路径DP(LeetCode例题全解析)
笔记·算法·leetcode·面试·职场和发展·动态规划·推荐算法
一只旭宝9 小时前
数据结构与算法复习手册:从写过,到讲清楚
开发语言·数据结构·c++·算法