[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
        
相关推荐
北冥有鱼被烹1 小时前
Linux timeout 命令完全指南:指定固定时间并发送固定信号
python
.道阻且长.1 小时前
C++ 11:可变参数模板
前端·c++·算法
SunnyDays10111 小时前
如何使用 Python 将 PowerPoint(PPT 或 PPTX)转换为 Markdown
python·ppt转markdown·pptx转markdown·powerpoint转md
PiaoKe___1 小时前
云手机原理与 Python 自动化实战:ADB、REST API、WebSocket 群控入门
python·智能手机·自动化
co_wait1 小时前
Python 迭代器(一)
python
Yolanda_20223 小时前
15.dataloader的使用
python
Doubbbbbbble云4 小时前
基于贪心算法的区间覆盖问题求解策略4
算法·贪心算法
不会就选b10 小时前
算法日常・每日刷题--<贪心>25
数据结构·算法
杨杨杨大侠10 小时前
Jev、Kev、Laya:决策模型怎么选,什么时候需要微调?
人工智能·python·agent
LOVE️YOU10 小时前
Python 在定义函数时,究竟定义的是什么?
python