[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
        
相关推荐
Hello world.Joey8 分钟前
OSTrack
人工智能·算法·目标检测·目标跟踪
迁旭12 分钟前
prompt_toolkit 3.0.52 API 参考手册
python
WL_Aurora15 分钟前
Python 算法基础篇之堆和优先队列
python·算法
早日退休!!!15 分钟前
PyTorch适配NPU
人工智能·pytorch·python
努力努力再努力wz16 分钟前
【MySQL进阶系列】一文打通事务机制:从锁、Undo Log 到 MVCC 与隔离级别
c语言·数据结构·数据库·c++·mysql·算法·github
薇茗19 分钟前
【初阶数据结构】 左右逢源的分支诗律 二叉树1
c语言·数据结构·算法
澈20722 分钟前
C++ string全面解析:从入门到精通
数据结构·c++·算法
刀法如飞24 分钟前
一款开箱即用的Flask 3.0 MVC工程脚手架,面向AI开发
后端·python·flask
xingpanvip28 分钟前
星盘接口开发文档:组合三限盘接口指南
android·开发语言·前端·python·php·lua
码农的神经元42 分钟前
拆解 SDGT 算法:图神经网络 + Transformer 如何做短期电力负荷预测
神经网络·算法·transformer