1. 程式人生 > >LeetCode -- ReverseBits 二進位制反轉問題 (Python 二進位制、整數相互轉化)

LeetCode -- ReverseBits 二進位制反轉問題 (Python 二進位制、整數相互轉化)

首先看一下二進位制與證書之間的相互轉化

整數轉二進位制:


1、採用%2的方式計算  
2、採用python自帶了方法 bin().  
比如bin(10) 回返回字符串'0b1010' ,只留下‘0’,‘1’序列需要把‘0b’去掉.  
bin(number).replace('0b','') 或bin(number)[2:]  
>>> bin(10)                     # 為了下邊表示方便 放入t中  
'0b1010'  

二進位制轉整數:

>>> int(t[2:],2)  
10  

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?
Related problem: Reverse Integer

class Solution(object):
    def reverseBits(self, n):
        """
        :type n: int
        :rtype: int
        """
        b = bin(n)
        print(b)

        # 不到32位,變成32位
        if len(b) < 34:
            b = '0b' + '0' * (34 - len(b)) + b[2:]

        print(b)
        reversed_b = "0b" + b[2
:][::-1] return int(reversed_b, 2) if __name__ == '__main__': print(Solution().reverseBits(43261596))