[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
        
相关推荐
飞Link8 分钟前
大模型时代的“语言编程”:Prompt Engineering (提示词工程) 深度解析与实战指南
开发语言·python·prompt
无限进步_15 分钟前
【C++】巧用静态变量与构造函数:一种非常规的求和实现
开发语言·c++·git·算法·leetcode·github·visual studio
郝学胜-神的一滴26 分钟前
Socket实战:从单端聊天到多用户连接的实现秘籍
服务器·开发语言·python·网络协议·pycharm
zzwq.30 分钟前
线程池与进程池:concurrent.futures高效并发
python
小超超爱学习993732 分钟前
大数乘法,超级简单模板
开发语言·c++·算法
Ricardo-Yang1 小时前
SCNP语义分割边缘logits策略
数据结构·人工智能·python·深度学习·算法
凌波粒1 小时前
LeetCode--344.反转字符串(字符串/双指针法)
算法·leetcode·职场和发展
啊哦呃咦唔鱼1 小时前
LeetCode hot100-543 二叉树的直径
算法·leetcode·职场和发展
soragui1 小时前
【Python】第 4 章:Python 数据结构实现
数据结构·windows·python
和小潘一起学AI1 小时前
CentOS 7安装Anaconda
开发语言·python