[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
        
相关推荐
不染尘.2 分钟前
二叉树相关题目
开发语言·数据结构·c++·算法
Imxyk16 分钟前
力扣:632. 最小区间(贪心)
java·数据结构·算法
Mr_Xuhhh21 分钟前
递归和迭代的区别(C/C++实现)
算法
知行合一。。。23 分钟前
程序中的log4j、stderr、stdout日志
python·单元测试·log4j
历程里程碑23 分钟前
21:重谈重定义理解一切皆“文件“及缓存区
linux·c语言·开发语言·数据结构·c++·算法·缓存
2501_9011478325 分钟前
PyTorch DDP官方文档学习笔记(核心干货版)
pytorch·笔记·学习·算法·面试
wxin_VXbishe25 分钟前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·spring boot·python·spring·django·php
sg_knight26 分钟前
原型模式(Prototype)
python·设计模式·开发·原型模式
Daydream.V28 分钟前
决策树三中分类标准
算法·决策树·分类
weixin_4331793329 分钟前
Python - 软件对象
开发语言·python