[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
        
相关推荐
故以往之不谏几秒前
快慢双指针算法--数组删除目标元素--LeetCode27
开发语言·数据结构·c++·算法·leetcode·学习方法·数组
王小义笔记4 分钟前
解决 uvloop 编译失败问题
python
AI科技星5 分钟前
空间光速螺旋动力学:统一质量、引力、电磁与时空本源的公理化理论与全现象验证
c语言·开发语言·opencv·算法·r语言
zhengzhengwang6 分钟前
chrome v8 内存管理机制
jvm·chrome·算法
im_AMBER6 分钟前
Leetcode 140 括号生成 | 单词搜索
算法·leetcode
njsgcs6 分钟前
空间中最后一条折弯线垂直于第一条折弯线
算法
qq_404265837 分钟前
C++中的代理模式实战
开发语言·c++·算法
进击的雷神9 分钟前
AJAX动态参数反爬、HTML嵌套网站提取、UPSERT增量更新、空值智能处理——沙特塑料展爬虫四大技术难关攻克纪实
爬虫·python·ajax·html
玛卡巴卡ldf9 分钟前
【LeetCode 手撕算法】(滑动窗口) 3-无重复字符的最长子串、438-找到字符串中所有字母异位词
数据结构·算法·leetcode·哈希算法
1941s9 分钟前
05-Agent 智能体开发实战指南(五):中间件系统与动态提示词
人工智能·python·中间件·langchain