[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 分钟前
C语言预处理详解:从宏到条件编译
c语言·笔记·算法
cpp_25017 分钟前
P10377 [GESP202403 六级] 好斗的牛
数据结构·c++·算法·题解·洛谷·gesp六级
邪修king7 分钟前
C++ 红黑树自平衡核心:旋转变色、规则详解与 STL 选型逻辑
数据结构·c++·b树·算法
一位代码1 小时前
微软开源项目MarkitDown:一款将pdf/word/ppt等各类文件转换为Markdown格式的python工具
python
随意起个昵称2 小时前
线性dp-计数类题目10(ZBRKA)
算法·动态规划
Navigator_Z8 小时前
LeetCode //C - 1089. Duplicate Zeros
c语言·算法·leetcode
Unbelievabletobe8 小时前
解决了股票api接口盘后数据更新慢的问题
大数据·开发语言·python
lpd_lt9 小时前
AI Coding的常用Prompt技巧
python·ai·ai编程
小江的记录本9 小时前
【JVM虚拟机】堆内存分代模型:年轻代(Eden+Survivor)、老年代、元空间Metaspace(附《思维导图》+《面试高频考点清单》)
java·前端·jvm·后端·python·spring·面试
在繁华处9 小时前
Java从零到熟练(三):流程控制
java·开发语言·python