[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
        
相关推荐
逆境不可逃3 分钟前
LeetCode 热题 100 之 215. 数组中的第K个最大元素 347. 前 K 个高频元素 295. 数据流的中位数
算法·leetcode·职场和发展
Shining05965 分钟前
AI 编译器系列(三)《PyTorch 中图优化》
人工智能·pytorch·python·深度学习·学习·机器学习·infinitensor
凤年徐7 分钟前
优选算法——滑动窗口
c++·算法
普通网友8 分钟前
SQL Server 2019安装详细教程(图文详解,非常靠谱)
后端·python·flask
DDzqss11 分钟前
3.14打卡day35
算法
WHS-_-202213 分钟前
mCore: Achieving Sub-millisecond Scheduling for 5G MU-MIMO Systems
java·算法·5g
浅念-19 分钟前
C++11 核心知识点整理
开发语言·数据结构·c++·笔记·算法
ruanyongjing24 分钟前
Python中的简单爬虫
爬虫·python·信息可视化
炽烈小老头25 分钟前
【 每天学习一点算法 2026/03/14】二叉搜索树中第K小的元素
学习·算法
echome88825 分钟前
Python 装饰器详解:从入门到实战的完整指南
开发语言·python