算法:190. Reverse Bits翻转比特或者整数

190. Reverse Bits

Reverse bits of a given 32 bits unsigned integer.

Note:

Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.
Follow up:

If this function is called many times, how would you optimize it?

Example 1:

Input: n = 00000010100101000001111010011100
Output:    964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: n = 11111111111111111111111111111101
Output:   3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.

Constraints:

The input must be a binary string of length 32

解法

方法一:一点一点
直觉

虽然这个问题并不难,但它经常作为面试开始的热身问题。重点是测试一个人对数据类型和位操作的基本知识。

作为人们在采访中可以提出的最直观的解决方案之一,可以将比特一点一点地颠倒过来。
在这里插入图片描述
听起来很简单,上述直觉可能会导致相当多的实现变体。例如,要检索整数中最右边的位n,可以应用模运算(即 n % 2)或位与运算(即 n & 1)。另一个例子是为了组合反转位的结果(例如 2^a, 2^b2),也可以使用加法运算(即 2^a + 2^b2)或再次位或运算(即 2^a | 2^b2)。

算法

这里我们展示了基于上述直觉的实现示例。
在这里插入图片描述
关键思想是,对于位于 index 的位i,在反转后,其位置应该是31-i(注意:索引从零开始)。

我们遍历输入整数的位串,从右到左(即 n = n >> 1)。为了检索整数的最右边位,我们应用位 AND 运算 ( n & 1)。

对于每一位,我们将其反转到正确的位置(即 (n & 1) << power)。然后我们将这个反转位累加到最终结果。

当没有剩下的位(即 n == 0)时,我们终止迭代。

class Solution:
    def reverseBits(self, n: int) -> int:
        ret, power = 0, 31
        while n:
            ret += (n & 1) << power
            n = n >> 1
            power -= 1
        return ret

参考

https://leetcode.com/problems/reverse-bits/solution/

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值