190. Reverse Bits [easy] (Python)

題目鏈接

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章