[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
        
相关推荐
凯瑟琳.奥古斯特6 分钟前
力扣1016高效解法:剪枝优化技巧
开发语言·c++·算法·leetcode·职场和发展
xiangyun6137 分钟前
C++ priority_queue 底层:手撕二叉堆与 Top K 问题
c++·算法·面试·stl·1024程序员节
databook39 分钟前
时间序列数据中,如何找出缺失值
python·数据分析
qz_Serene1 小时前
练习算法题:双指针 -cpp
c++·算法·leetcode·1024程序员节
小小龙学IT2 小时前
Python Polars 高性能数据处理引擎深度解析
开发语言·python·rust·1024程序员节
Nuanyt2 小时前
Hot 100 刷题笔记 · 数组与哈希专题(3 题)
java·笔记·算法·leetcode·哈希算法·1024程序员节
csdn_aspnet2 小时前
JavaScript 未排序数组中第 k 个最小/最大元素 (预期线性时间)
python
quantdash_cc2 小时前
如何利用标的信息为研究股票池补充名称和交易所信息?
开发语言·python·pandas·量化交易·1024程序员节·股票数据·quantdash
数字化转型分享点滴2 小时前
机加工企业上大数据分析系统有哪些容易踩的坑?
python·1024程序员节
碧海银沙音频科技研究院2 小时前
基于炬芯平台ATS308X多模型兼容语音识别算法
人工智能·算法·语音识别