[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
        
相关推荐
Sumerking几秒前
llc_control.c 专项评审(v3 更新版)
c语言·开发语言·算法·obc
软行22 分钟前
LeetCode 每日一题 3876. 构造奇偶一致的数组 II
c++·算法·leetcode
轩情吖37 分钟前
Python基础知识点完整总结
python·字符串·编程语言·函数·列表·元组·字典
绿算技术1 小时前
Solidigm联合绿算技术共同发布《面向 SOHO AI 推理的存储扩展方案》技术白皮书
人工智能·科技·算法·架构·spark
青 春 记 忆1 小时前
零基础入门python69:为 FastAPI 项目构建可复现 Docker 镜像
python·fastapi·后端开发
<花开花落>1 小时前
Python 项目迁移到 uv:经验小结与可复用工作流
python·uv
databook1 小时前
正态分布撒谎时:用柯西分布捕捉生活中的“黑天鹅”
python·数据挖掘·数据分析
Java后端的Ai之路1 小时前
LangChain Deep Agents 从入门到企业实战
开发语言·人工智能·python·langchain·deepagents
2601_962381581 小时前
Mac和Windows,哪种电脑适合新手学Python|数智码力分享
windows·python·mac·编程环境·学习入门
会飞的拖把1 小时前
Python文件操作详解:从文件读写到os、shutil模块实战
开发语言·python