[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
        
相关推荐
m沐沐6 分钟前
【深度学习】YOLOv2目标检测算法——改进点、网络结构与聚类先验框解析
人工智能·pytorch·深度学习·算法·yolo·目标检测·transformer
不会就选b10 分钟前
算法日常・每日刷题--<链表>3
数据结构·算法·链表
geovindu37 分钟前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
郭老二2 小时前
【Python】基本语法:装饰器语法糖@
python
Zachery Pole3 小时前
CCF-CSP备战NO.7【队列】
算法
闪电悠米3 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展
_Jimmy_3 小时前
Agent常用检索器的详细介绍
python·langchain
满天星83035773 小时前
【算法】最长递增子序列(三种解法)
算法
小柯南敲键盘3 小时前
图片翻译API接入与自动化实现指南
运维·python·自动化
旅僧4 小时前
Q-learning(自用)
python·机器学习