JonnyF--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 as00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

Related problem: Reverse Integer

解题思路:

      对于这道题,我们只需要把要翻转的数从右向左一位位的取出来,然后加到新生成的数的最低位即可。但是在这里我并没有使用这种方式,而是采用的第二种方式,这种方式是通过位运算符将数与相反的数进行计算得出反转后的结果。

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        s = 0
        for i in range(32):
            if (n & (0x1 << i)) >> i:
                s += 0x1 << (31-i)
        return s
posted @ 2015-05-14 10:42  F-happy  阅读(105)  评论(0)    收藏  举报