[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
        
相关推荐
顶点多余4 小时前
那些在算法中适合巩固的知识点---1
java·前端·算法
lupai5 小时前
手机在网状态接口实测效果与质量评估
大数据·python·智能手机·api接口
罗西的思考6 小时前
【Agentic RL / 强化学习框架】Molt 设计解读
人工智能·算法·机器学习
hahaha60166 小时前
HLS高层次综合设计技巧--C++类和模板
图像处理·人工智能·算法·计算机视觉
荷蒲6 小时前
【小白量化Qbuddy】用AI设计miniQMT指标公式计算量化平台
人工智能·python·机器人
阿童木写作6 小时前
跨境电商图片翻译工具,批量翻译视频字幕一键抠图
人工智能·python·音视频
多弗朗皮卡丘7 小时前
算法详解4:买卖股票的最佳时机系列(上)
算法
何以解忧,唯有..8 小时前
Pydantic 介绍与使用:Python 数据校验的现代方案
数据库·python·microsoft
又幸福了哥9 小时前
Python入门到高级(知识点七)
python
又幸福了哥9 小时前
Python入门到高级(知识点六)
python