[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
        
相关推荐
什巳4 分钟前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
宠友信息8 分钟前
消息序号如何保证即时通讯源码聊天记录稳定加载
java·spring boot·redis·python·mysql·uni-app
小柯南敲键盘44 分钟前
批量图片翻译与视频字幕一站式解决高效跨境电商沟通难题
大数据·人工智能·python·音视频
什巳2 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_796826523 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
吴梓穆4 小时前
Python 基础 正则表达式
python
巧克力男孩dd4 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法
爱刷碗的苏泓舒4 小时前
平方根信息滤波:矩阵推导及 GNSS 参数估计应用
线性代数·算法·矩阵·gnss·参数估计·测量平差·平方根信息滤波
闲猫5 小时前
LangChain / Core components / Models
开发语言·python·langchain
想做小南娘,发现自己是女生喵5 小时前
第 2 章 顺序表和 vector
java·数据结构·算法