[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
        
相关推荐
葫三生11 分钟前
《论三生原理》神话学构想与“神话历史”理论、《古史中的神话》思路异同?
大数据·人工智能·科技·深度学习·算法
2601_9623008116 分钟前
机器学习贴士:使用Python编写MapReduce
hadoop·python·机器学习·mapreduce·数据处理
liliangcsdn43 分钟前
因子分析指标概念与示例
算法·机器学习
xyz_CDragon1 小时前
GitHub上4个爆款AI开源Skill:拍照后不用P图,用Codex一键生成高级海报(附效果图+使用教程)
人工智能·python·github·codex·skill
weixin199701080161 小时前
[特殊字符]《跨境二手ERP对接Back Market:标准化API + 7~10工作日技术合规审核实录》(附Python源码)
开发语言·python·pandas
持敬chijing2 小时前
Python-数据类型-列表
开发语言·python·青少年编程
SupL!2 小时前
LoftQ原理
算法
2601_962301012 小时前
Python环境搭建及PyCharm破解使用技巧
python·pycharm·环境搭建·避坑技巧·破解使用
Navigator_Z3 小时前
LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares
c语言·算法·leetcode
稻米哟3 小时前
力扣100——双指针
算法·leetcode