[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
        
相关推荐
今天AI了吗3 分钟前
大模型技术全景(一):AI、机器学习、深度学习,三者的关系到底是什么?一文搞懂
数据库·人工智能·python·sql·深度学习·机器学习·rust
仙女修炼史19 分钟前
gradcam在yolo中的应用
人工智能·python·yolo
带多刺的玫瑰24 分钟前
Leecode#15刷题之三数之和
算法·leetcode·职场和发展
哭泣方源炼蛊39 分钟前
并查集进阶 P1(带权并查集,并查集分类)
数据结构·c++·算法·二进制·带权并查集
李可以量化1 小时前
Redis Client 从了解到精通(六):redis-py 服务控制与状态监控辅助函数详解
python
牧羊人.3331 小时前
动手学深度学习 02 | 手写数字识别
图像处理·人工智能·深度学习·算法
李可以量化1 小时前
Redis Client 从了解到精通(六)下:redis-py 时间、库管理与持久化辅助函数详解
python
晓窗科技1 小时前
AI基座哪家好
大数据·人工智能·python
武帝为此1 小时前
【InnoDB存储引擎介绍】
数据库·算法
麻雀飞吧1 小时前
学量化:看到“近期工具推荐”时,先问工具要解决什么问题
人工智能·python