[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
        
相关推荐
散峰而望3 分钟前
【算法竞赛】二叉树
开发语言·数据结构·c++·算法·深度优先·动态规划·宽度优先
AC赳赳老秦6 分钟前
新能源AI趋势:DeepSeek分析光伏/风电数据,助力2026新能源运维升级
运维·人工智能·python·安全·架构·prometheus·deepseek
Never_Satisfied15 分钟前
在c#中,缩放jpg文件的尺寸
算法·c#
那起舞的日子21 分钟前
卡拉兹函数
java·算法
颜酱23 分钟前
滑动窗口算法通关指南:从模板到实战,搞定LeetCode高频题
javascript·后端·算法
Stringzhua24 分钟前
队列-双端队列【Queue2】
java·数据结构·算法·队列
侧岭灵风30 分钟前
yolov5颈部网络图解
深度学习·算法·yolo
Learner__Q30 分钟前
GPT模型入门教程:从原理到实现
python·gpt
夕除35 分钟前
js--21
java·python·算法
冬夜戏雪36 分钟前
单词拆分/分割等和子集
算法·leetcode·职场和发展