Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10101111110010110010011101101001.
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 signed integer type and should not affect your implementation, as the internal binary representation of the integer 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?
解题思路:
这道题很简单,但是注意问题有一个点,我们通常在python里将一个数字字符串转换成int型的时候,直接int(数字字符串),其实int函数里面还有一个默认参数int(x, base=10)
即默认转换为10进制整型,当然也可以手动指定转换成其他进制。
例如:
int('12',16) # 如果是带参数base的话,12要以字符串的形式进行输入,12 为 16进制
python3代码实现:
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
s = str(bin(n))[2:][::-1]
return int(s +'0'*(32-len(s)), 2)