[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
        
相关推荐
练习时长一年7 分钟前
LeetCode热题100(爬楼梯)
算法·leetcode·职场和发展
寻星探路10 分钟前
【Python 全栈测开之路】Python 基础语法精讲(一):常量、变量与运算符
java·开发语言·c++·python·http·ai·c#
朔北之忘 Clancy16 分钟前
2020 年 6 月青少年软编等考 C 语言一级真题解析
c语言·开发语言·c++·学习·算法·青少年编程·题解
_codemonster16 分钟前
计算机视觉入门到实战系列(九) SIFT算法(尺度空间、极值点判断)
深度学习·算法·计算机视觉
智航GIS27 分钟前
10.5 PyQuery:jQuery 风格的 Python HTML 解析库
python·html·jquery
小兔崽子去哪了28 分钟前
机器学习,梯度下降,拟合,正则化,混淆矩阵
python·机器学习
缘友一世42 分钟前
PyCharm连接autodl平台服务(python解释器&jupyter lab)
python·jupyter·pycharm
a程序小傲1 小时前
得物Java面试被问:方法句柄(MethodHandle)与反射的性能对比和底层区别
java·开发语言·spring boot·后端·python·面试·职场和发展
sinat_286945191 小时前
AI Coding LSP
人工智能·算法·prompt·transformer
星马梦缘1 小时前
算法与数据结构
数据结构·c++·算法·动态规划·克鲁斯卡尔·kahn