[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
        
相关推荐
小陈phd14 小时前
多模态大模型学习笔记(七)——多模态数据的表征与对齐
人工智能·算法·机器学习
雨泪丶14 小时前
代码随想录算法训练营-Day35
算法
pursuit_csdn14 小时前
LeetCode 1022. Sum of Root To Leaf Binary Numbers
算法·leetcode·深度优先
nimadan1214 小时前
**AI漫剧软件2025推荐,解锁高性价比创意制作新体验**
人工智能·python
NAGNIP15 小时前
一文搞懂神经元模型是什么!
人工智能·算法
董董灿是个攻城狮15 小时前
AI 视觉连载6:传统 CV 之高斯滤波
算法
yunhuibin16 小时前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
散峰而望17 小时前
C++ 启程:从历史到实战,揭开命名空间的神秘面纱
c语言·开发语言·数据结构·c++·算法·github·visual studio
易辰君17 小时前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python