[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
        
相关推荐
楠秋9206 分钟前
代码随想录算法训练营第三十一天|56. 合并区间 、 738.单调递增的数字、968.监控二叉树
数据结构·算法·leetcode·贪心算法
MadPrinter35 分钟前
Python 异步爬虫实战:FindQC 商品数据爬取系统完整教程
爬虫·python·算法·自动化
清水白石00835 分钟前
Python 函数式编程实战:从零构建函数组合系统
开发语言·python
郝学胜-神的一滴37 分钟前
Effective Modern C++ 条款36:如果有异步的必要请指定std::launch::async
开发语言·数据结构·c++·算法
小此方40 分钟前
Re:从零开始的 C++ STL篇(六)一篇文章彻底掌握C++stack&queue&deque&priority_queue
开发语言·数据结构·c++·算法·stl
0 0 01 小时前
CCF-CSP 40-2 数字变换(transform)【C++】考点:预处理
开发语言·c++·算法
香芋Yu1 小时前
【强化学习教程——01_强化学习基石】第06章_Q-Learning与SARSA
人工智能·算法·强化学习·rl·sarsa·q-learning
回敲代码的猴子1 小时前
2月15日打卡
数据结构·算法
喵手1 小时前
Python爬虫实战:数据质量治理实战 - 构建企业级规则引擎与异常检测系统!
爬虫·python·爬虫实战·异常检测·零基础python爬虫教学·数据质量治理·企业级规则引擎
菜鸡儿齐1 小时前
leetcode-和为k的子数组
java·算法·leetcode