[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
        
相关推荐
sylviiiiiia2 分钟前
leetcode hot 100
python·算法·leetcode
半摆烂日常12 分钟前
自建WMS和买成品:三年成本对比
大数据·服务器·数据库·python·深度学习·低代码·numpy
2601_9622965130 分钟前
Python的哈希hashlib模块详细解读
python·md5·sha·加密算法·hashlib
chinesegf33 分钟前
comfyui便携版的基础使用
python
OPEN-F34 分钟前
ROS2系列教程:Gazebo插件(关节控制/IMU/激光雷达)
c++·python·数码相机·算法·机器人
临沂GEO41 分钟前
芝麻开门GEO|AI数字化新趋势,助力企业线上长效增长
大数据·人工智能·python
luj_176842 分钟前
虚实交融中的真实人物塑造
c语言·开发语言·网络·经验分享·算法
haolin123.1 小时前
STL vector底层揭秘:从构造到迭代器失效
开发语言·c++·算法
梦想不只是梦与想1 小时前
大模型系列(二):技术基础与核心能力
python·大模型·token
shehuiyuelaiyuehao1 小时前
算法37,位运算,两个整数之和(不用+符号)
算法