翻转给定的32位无符号整数的二进制位
Example:
Input: 43261596 Output: 964176192 Explanation: 43261596 represented in binary as 00000010100101000001111010011100, return 964176192 represented in binary as 00111001011110000010100101000000.
进阶:
如果多次调用你的函数,你该如何优化你的算法?
1:整数转二进制,翻转二进制之后再转整数
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
if n==0:
return 0
bits = self.intToBit(n)
return self.bitToInt(bits[::-1])
def intToBit(self, n): #整数转bit
bits = ""
while n>0:
bits = str(n%2) + bits
n = n//2
while len(bits)!=32:
bits = "0"+bits
return bits
def bitToInt(self, n): #bit转整数
sum = 0
for i in range(len(n)):
sum += int(n[i])*2**(len(n)-i-1)
return sum
2:利用format()和int()方法(也可以把format()换位bin()参考他人代码)
def reverseBits(self, n):
bits = "{:0>32b}".format(n)
return int(bits[::-1], 2)
算法来自:https://leetcode-cn.com/problems/reverse-bits/description/