[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
        
相关推荐
Lupino几秒前
贪小便宜买的 10 元“三无”传感器,看我用 OpenClaw 强行逆袭!
python·ai编程
不染尘.21 分钟前
字符串哈希
开发语言·数据结构·c++·算法·哈希算法
Java.慈祥26 分钟前
My First AI智能体!!!
人工智能·python·ai编程·智能体·coze·coze工作流·agent开发
今儿敲了吗27 分钟前
25| 丢手绢
数据结构·c++·笔记·学习·算法
qq_242188633227 分钟前
【零基础使用Trae CN编写第一个AI游戏教程】
开发语言·前端·人工智能·python·游戏·html
小雨中_29 分钟前
4.1 LLaMA 系列:从 LLaMA-1 到 LLaMA-3
人工智能·python·深度学习·机器学习·自然语言处理·llama
小鸡吃米…29 分钟前
TensorFlow 模型导出
python·tensorflow·neo4j
wostcdk34 分钟前
归并排序 & 逆序对
数据结构·算法
weixin_4772716936 分钟前
第八正:治(马王堆帛书《老子》3)
算法·图搜索算法
无水先生37 分钟前
python应用的参数管理(2):argparse 函数的用法
网络·数据库·python