题目链接
https://leetcode.com/problems/reverse-bits/
题目原文
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(二进制表示为00000010100101000001111010011100),返回964176192(二进制表示为00111001011110000010100101000000)。
进一步:如果该函数被多次调用,你该如何优化它?
思路方法
思路一
先将输入转换成2进制字符串,再翻转并扩充到32位,再将此32位的二进制转为无符号整数即可。利用Python的bin()函数很方便。
代码
class Solution(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
b = bin(n)[:1:-1]
return int(b + ‘0‘*(32-len(b)), 2)
思路二
按位处理,将输入n的二进制表示从低位到高位的值依次取出,逆序排列得到翻转后的值。这里更新res的时候,用纯位操作会比用加法要快的多。
代码
class Solution(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
res = 0
for i in xrange(32):
res <<= 1
res |= ((n >> i) & 1)
return res
思路三
还有一种看起来比较暴力,其实也比较巧妙的方法。类似二分的思想,每次处理一半的位交换,具体看代码吧。
代码
class Solution(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
n = (n >> 16) | (n << 16);
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
return n
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51705094