[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
        
相关推荐
stolentime1 分钟前
SOS DP学习笔记
c++·笔记·学习·算法·贪心算法·动态规划·二进制
水母量化5 分钟前
量化收益率计算别混用:算术均值、几何均值与对数收益
算法·均值算法·量化交易
是Yu欸32 分钟前
先让 T1 Pro 传回一张好用的图:JPEG 抓拍、RTSP 视频与方向校正
python·机器人·音视频
伞伞悦读35 分钟前
【第60期】特征值不是重要性:Python 特征分解与 PCA 的前置判断
python
xunberg36 分钟前
【生命科学 Agent】推理平台(三)
算法·程序员·架构
INGNIGHT37 分钟前
151 · 买卖股票的最佳时机 III(序列dp)
数据结构·算法·leetcode
庖丁解牛41 分钟前
十进制转二进制:凑数法(填1法)
算法
2601_9679801142 分钟前
Python之wxPython模块的安装
linux·windows·python·wxpython·gui设计·1024程序员节
行者全栈架构师1 小时前
【共创稿事节】双引擎智能相册:HarmonyOS 7(API 26)文搜图 × 图像超分端侧 AI 联动实战
前端·算法·架构
云南新人和数采集团1 小时前
DeepSeek Harness 开源贡献手记:从入门到合入主线
python·开源·github