[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
        
相关推荐
光羽隹衡3 分钟前
决策树项目——电信客户流失预测
算法·决策树·机器学习
TL滕4 分钟前
从0开始学算法——第二十一天(高级链表操作)
笔记·学习·算法
CoovallyAIHub4 分钟前
无人机低空视觉数据集全景解读:从单机感知到具身智能的跨越
深度学习·算法·计算机视觉
学编程就要猛4 分钟前
算法:1.移动零
java·算法
杜子不疼.4 分钟前
【LeetCode 35 & 69_二分查找】搜索插入位置 & x的平方根
算法·leetcode·职场和发展
YYDS3145 分钟前
次小生成树
c++·算法·深度优先·图论·lca最近公共祖先·次小生成树
xu_yule8 分钟前
算法基础(区间DP)
数据结构·c++·算法·动态规划·区间dp
天骄t9 分钟前
信号VS共享内存:进程通信谁更强?
算法
biter down11 分钟前
C++ 交换排序算法:从基础冒泡到高效快排
c++·算法·排序算法
540_54011 分钟前
ADVANCE Day27
人工智能·python·机器学习