[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
        
相关推荐
漂流瓶jz9 小时前
UVA-11846 找座位 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·排序算法·深度优先·aoapc·算法竞赛入门经典·uva
m0_564876849 小时前
提示词工程手册学习
人工智能·python·深度学习·学习
米粒19 小时前
力扣算法刷题 Day 31 (贪心总结)
算法·leetcode·职场和发展
少许极端9 小时前
算法奇妙屋(四十)-贪心算法学习之路7
java·学习·算法·贪心算法
波诺波9 小时前
p1项目system_model.py代码
开发语言·python
静心观复10 小时前
Python 虚拟环境与 pipx 详解
开发语言·python
卷心菜狗10 小时前
Re.从零开始使用Python构建本地大模型网页智慧聊天机器人
开发语言·python·机器人
AlenTech10 小时前
647. 回文子串 - 力扣(LeetCode)
算法·leetcode·职场和发展
py有趣10 小时前
力扣热门100题之合并两个有序链表
算法·leetcode·链表
书到用时方恨少!10 小时前
Python NumPy 使用指南:科学计算的基石
开发语言·python·numpy