[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
        
相关推荐
Navigator_Z21 分钟前
LeetCode //C++ - 1226. The Dining Philosophers
c语言·算法·leetcode
昭昭日月明26 分钟前
RAGFlow 入门,不用从零造轮子
python·ai编程
FOORIR29 分钟前
3D视觉+AI客流系统怎么做:从Sensor Pipeline到数据事件引擎
算法
莓有烦恼吖1 小时前
Vibe Coding 的一些思考
python
小白学大数据1 小时前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel
爱丶不疚2 小时前
写给前端工程师的现代 Python 工程化最佳实践:从 pnpm 到 uv,从 CommonJS 到 src-layout
javascript·python·typescript
2601_962297252 小时前
C# vs Java vs Python:YOLO工业部署性能对比实战
java·python·c·工业视觉·性能对比
CTA终结者2 小时前
示例、拆解和练习,要连成一条量化补课线
人工智能·python
lolijiaqi152 小时前
一线观察:长期体验后发现的医疗器械 CDMO 底层现象
大数据·python
Omics Pro2 小时前
Arc研究所Cell|全新虚拟细胞官方基准评测框架
大数据·人工智能·深度学习·算法·机器学习