1. 程式人生 > >Leetcode 190:顛倒二進位制位(超詳細的解法!!!)

Leetcode 190:顛倒二進位制位(超詳細的解法!!!)

顛倒給定的 32 位無符號整數的二進位制位。

示例 1:

輸入: 00000010100101000001111010011100
輸出: 00111001011110000010100101000000
解釋: 輸入的二進位制串 00000010100101000001111010011100 表示無符號整數 43261596,
      因此返回 964176192,其二進位制表示形式為 00111001011110000010100101000000。

示例 2:

輸入:11111111111111111111111111111101
輸出:10111111111111111111111111111111
解釋:輸入的二進位制串 11111111111111111111111111111101 表示無符號整數 4294967293,
      因此返回 3221225471 其二進位制表示形式為 10101111110010110010011101101001。

提示:

  • 請注意,在某些語言(如 Java)中,沒有無符號整數型別。在這種情況下,輸入和輸出都將被指定為有符號整數型別,並且不應影響您的實現,因為無論整數是有符號的還是無符號的,其內部的二進位制表示形式都是相同的。
  • 在 Java 中,編譯器使用二進位制補碼記法來表示有符號整數。因此,在上面的 示例 2 中,輸入表示有符號整數 -3,輸出表示有符號整數 -1073741825

進階:
如果多次呼叫這個函式,你將如何優化你的演算法?

解題思路

這個問題使用python的話非常取巧,只要將輸入的整數轉化為二進位制字串,然後reverse後再轉換回整數即可。

class
Solution: # @param n, an integer # @return an integer def reverseBits(self, n): bin_str = '{:0>32b}'.format(n) return int(bin_str[::-1], 2)

正常的套路是這樣的。

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        res = 0
        for
_ in range(32): res = (res << 1) + (n & 1) n >>= 1 return res

一個非常Hacker的程式碼

class Solution 
{
public:
    uint32_t reverseBits(uint32_t n) 
    {
        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;
    }
};

假設輸入數字的二進位制是abcdefgh,上述程式碼實現了這樣的操作

abcdefgh -> efghabcd -> ghefcdab -> hgfedcba

也就是一個歸併排序的過程。非常酷!!!

reference:

https://leetcode.com/problems/reverse-bits/discuss/54741/O(1)-bit-operation-C%2B%2B-solution-(8ms)

我將該問題的其他語言版本新增到了我的GitHub Leetcode

如有問題,希望大家指出!!!