算法:190. Reverse Bits翻转比特或者整数
Posted 架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: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/
以上是关于算法:190. Reverse Bits翻转比特或者整数的主要内容,如果未能解决你的问题,请参考以下文章