美文网首页
190. Reverse Bits

190. Reverse Bits

作者: 金发萌音 | 来源:发表于2015-05-02 23:40 被阅读37次

    题目

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

    挺简单的 直接上代码

    #coding:utf-8
    
    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            keep = ""
            while(n != 0):
                if(n % 2 == 1):
                    keep += "1"
                else:
                    keep += "0"
                n = n / 2
    
            # keep = keep[::-1]
    
            temp = ""
            i = 32 - len(keep)
            while i >0 :
                temp += "0"
                i -= 1
            keep =  keep + temp
    
            orgin = 0
            length = len(keep) -1
    
            for i in keep:
                if i == "1":
                    orgin += pow(2,length)
                length -= 1
    
            return orgin
    
    if __name__ == "__main__":
        test = Solution()
        print test.reverseBits(43261596)
    

    相关文章

      网友评论

          本文标题:190. Reverse Bits

          本文链接:https://www.haomeiwen.com/subject/gjibfttx.html