声明:题目解法使用c++和Python两种,重点侧重在于解题思路和如何将c++代码转换为python代码。
题目
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
题意
给你一个32位无符号整数,求出它的反向位(即二进制的逆序得到的整数)
思路
主要注意的点:必须是32位
例如2的二进制为 10
逆序为:01
= 1
要是这么理解你就错了,仔细看题意,正确的结果要的是:01000000000000000000000000000000
2的31次方(不要以为超出int范围,题意说了是无符号)。
博主的思路是先求出逆序保存在数组中,然后不满32位,补0。
解法一: C++版
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int res = 0;
int a[32] = {0},k = 0;
while(n)
{
a[k++] = n % 2;
n /= 2;//除以2
}
for (int i=0;i<32;i++)
res = res * 2 + a[i];
return res;
}
};
运行时间:
但是,题意还说:
If this function is called many times, how would you optimize it?
如果这个函数被多次调用,如何优化它?
博主首先想到了是位运算,修改后的代码:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
int a[32] = {0},k = 0;
while(n)
{
a[k++] = n % 2;
n = n >> 1;//除以2
}
//注意 <<的运算级小于 + 的运算级
for (int i=0;i<32;i++)
res = (res << 1) + a[i];
return res;
}
};
运行时间:
果然时间缩短了一半。
下面是博主在九章算术看到了特别简洁的代码,原代码是java版的,下面是改成了c++版。
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
for (int i=0;i<32;i++)
{
res = (res << 1) | (n & 1);
n = (n >> 1);
}
return res;
}
};
- n&1 : n和1做“按位与”运算,1的二进制只有末位是1,所以n&1就是只保留n的末位(二进制)。同时n&1就表示了n的奇偶性。
- | : 如果存在于任一操作数中,二进制 OR 运算符复制一位到结果中。
例如:
假设如果 A = 60,且 B = 13,现在以二进制格式表示,它们如下所示:
A = 0011 1100
B = 0000 1101
(A | B) 将得到 61,即为 0011 1101
运行时间:
解法二: Python版
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
res = 0
for i in range(0,32):
res = (res << 1) | (n & 1)
n = (n >> 1)
return res
运行时间:
GitHub本题题解:https://github.com/xuna123/LeetCode/blob/master/Leetcode%23190.%20Reverse%20Bits%20.md