[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
        
相关推荐
liwulin05065 分钟前
【PYTHON-YOLOV8N】yoloface+pytorch+cnn进行面部表情识别
python·yolo·cnn
Maỿbe7 分钟前
力扣hot图论部分
算法·leetcode·图论
LYFlied15 分钟前
【每日算法】LeetCode 78. 子集
数据结构·算法·leetcode·面试·职场和发展
月明长歌19 分钟前
【码道初阶】【Leetcode606】二叉树转字符串:前序遍历 + 括号精简规则,一次递归搞定
java·数据结构·算法·leetcode·二叉树
子枫秋月20 分钟前
C++字符串操作与迭代器解析
数据结构·算法
鹿角片ljp20 分钟前
力扣234.回文链表-反转后半链表
算法·leetcode·链表
(●—●)橘子……21 分钟前
记力扣1471.数组中的k个最强值 练习理解
数据结构·python·学习·算法·leetcode
oioihoii24 分钟前
C++共享内存小白入门指南
java·c++·算法
_OP_CHEN25 分钟前
用极狐 CodeRider-Kilo 开发俄罗斯方块:AI 辅助编程的沉浸式体验
人工智能·vscode·python·ai编程·ai编程插件·coderider-kilo
Bruce_kaizy26 分钟前
c++图论————图的基本与遍历
c++·算法·图论