[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
        
相关推荐
样例过了就是过了15 小时前
LeetCode热题100 最大子数组和
数据结构·算法·leetcode
铸人15 小时前
再论自然数全加和 - 欧拉伽马常数
数学·算法·数论·复数
m0_5312371715 小时前
C语言-变量,枚举常量,字符串,打印类型,转义字符
c语言·数据结构·算法
张3蜂15 小时前
Python venv 详解:为什么要用、怎么用、怎么用好
开发语言·python
zyeyeye15 小时前
自定义类型:结构体
c语言·开发语言·数据结构·c++·算法
老赵全栈实战15 小时前
《从零搭建RAG系统第3天:文档加载+文本向量化+向量存入Milvus》
python
火龙果研究院15 小时前
在CentOS上安装Python 3.13需要从源码编译
开发语言·python·centos
俩娃妈教编程16 小时前
2023 年 03 月 二级真题(1)--画三角形
c++·算法·双层循环
龙山云仓16 小时前
No156:AI中国故事-对话司马迁——史家绝唱与AI记忆:时间叙事与因果之链
大数据·开发语言·人工智能·python·机器学习
niuniudengdeng16 小时前
一种基于高维物理张量与XRF实景复刻的一步闭式解工业级3D打印品生成模型
人工智能·python·数学·算法·3d