1. 程式人生 > >Python實現"顛倒二進位制位"的兩種方法

Python實現"顛倒二進位制位"的兩種方法

翻轉給定的32位無符號整數的二進位制位

Example:

Input: 43261596
Output: 964176192
Explanation: 43261596 represented in binary as 00000010100101000001111010011100, 
             return 964176192 represented in binary as 00111001011110000010100101000000.

進階:

如果多次呼叫你的函式,你該如何優化你的演算法?

1:整數轉二進位制,翻轉二進位制之後再轉整數

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        if n==0:
            return 0
        bits = self.intToBit(n)
        return self.bitToInt(bits[::-1])
        
    def intToBit(self, n):    #整數轉bit
        bits = ""
        while n>0:
            bits = str(n%2) + bits
            n = n//2
        while len(bits)!=32:
            bits = "0"+bits
        return bits
    
    def bitToInt(self, n):     #bit轉整數
        sum = 0
        for i in range(len(n)):
            sum += int(n[i])*2**(len(n)-i-1)
        return sum

2:利用format()和int()方法(也可以把format()換位bin()參考他人程式碼)

def reverseBits(self, n):
        bits = "{:0>32b}".format(n)
        return int(bits[::-1], 2)