Problem
Reverse bits of a given 32 bits unsigned integer.
https://leetcode.com/problems/reverse-bits/
Follow up:
If this function is called many times, how would you optimize it?
Note
idea#1 字符串翻转
受上一道翻转整数的思路2影响,第一反应是将输入的32位无符号整数转化成二进制字符串进而进行翻转操作。
code1 16ms
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
n = bin(n)[2:] #转化为二进制字符串‘0bxxxxxxx’,去掉前两位
rev_n = ('0'*(32-len(n)) + n)[::-1] #补全32位并进行翻转
return int(rev_n, 2) #第二个参数代表原数为二进制
code2 参考(推荐)
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
n="{0:032b}".format(n) #格式化输出 从0起填充0 32表示长度 b表示二进制(d十 o八 x十六)
return int(n[::-1],2) #2代表原数为二进制
idea#2 位移法
随即思考二进制的一大特点在于可以进行移位操作,将输入二进制自右按位取出(不断右移取出最低位(&1)),依次左移赋值给新的二进制数(赋值最低位并不断左移),即可得到翻转结果。
code 16ms
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n): #根据题意判断n应为十进制Int
rev_n = 0
for i in range(32):
rev_n <<= 1 #十进制转成二进制进行左移
rev_n += (n >> i & 1)
#rev_n |= (n >> i & 1)
return rev_n
Summary
- python切片操作https://blog.csdn.net/xpresslink/article/details/77727507
- python格式化输出format()函数 https://www.runoob.com/python/att-string-format.html
- int型转化成二进制时为32位前面自动补零