题目:
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位二进制串翻转后对应的十进制数。例如,十进制数43261596对应的32位二进制串为00000010100101000001111010011100,翻转后的二进制串为00111001011110000010100101000000,该二进制串对应的十进制数为964176192 ,返回964176192
代码:
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
if n == 0 :
return 0
else :
bin_list = [] #记录二进制串
for i in range(32) : #整除32次,每次记录模2的余数,得到的即为翻转后的二进制串
bin_list.append(n%2)
n = n/2
bin_list = bin_list[::-1] #将二进制串继续翻转,将低位放在左端,用于从左到右转化为十进制数
result = 0
for i in range(32) : #对第i位,如果为1,转化为十进制,即为2的i次方
if bin_list[i] == 1 :
result += 2**i
return result
笔记:
现在看这道题,好像没难点,一次过,而且效率也还行:
Submission Details
600 / 600 test cases passed.
| Status: Accepted |
Runtime:
39 ms
|
Submitted:
0 minutes ago
|
Accepted Solutions Runtime Distribution