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(バイナリは000001001001010001111011001001001011100として表される)は、964176192(バイナリは00011001011110010010010010100000として表される)を返す.さらに:関数が複数回呼び出された場合、どのように最適化しますか?
考え方
考え方1
入力を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)

考え方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