[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
        
相关推荐
稚辉君.MCA_P8_Java11 分钟前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*15 分钟前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
不知更鸟1 小时前
前端报错:快速解决Django接口404问题
前端·python·django
4***72131 小时前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
梁正雄1 小时前
1、python基础语法
开发语言·python
.YM.Z1 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
Chat_zhanggong3451 小时前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法
百***48072 小时前
【Golang】slice切片
开发语言·算法·golang
墨染点香2 小时前
LeetCode 刷题【172. 阶乘后的零】
算法·leetcode·职场和发展
做怪小疯子2 小时前
LeetCode 热题 100——链表——反转链表
算法·leetcode·链表