[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
        
相关推荐
华研前沿标杆游学2 小时前
华为松山湖高阶研学|企业数字化转型游学攻略
python
ting94520006 小时前
Humalike X Hermes 深度技术剖析:单指令注入群聊社交智能的底层架构、算法与跨 IM 平台实现
人工智能·算法·架构
Data_Journal6 小时前
用于网页抓取的 Node-unblocker
大数据·开发语言·数据库·python·scrapy
吴声子夜歌6 小时前
Java面试——算法
java·算法·面试
豆角焖肉7 小时前
SSM 聚合项目搭建:多 Maven 模块项目
开发语言·python·pycharm
h_a_o777oah7 小时前
【图论】Tarjan 缩点:解决有向图中环的问题
c++·算法·图论·acm·强连通分量·缩点·tarjan
Tisfy7 小时前
LeetCode 1386.安排电影院座位:哈希表+位运算
算法·leetcode·散列表·题解·哈希表
青 春 记 忆7 小时前
零基础入门python20:Flask配置、扩展和蓝图拆分
python·flask·后端开发
Nil2088 小时前
leetcode 199二叉树的右视图
算法·leetcode·深度优先
m0_380743878 小时前
为 OpenAI 兼容接口配置教程
开发语言·python·node.js