1. 程式人生 > >[Swift]LeetCode190. 顛倒二進位制位 | Reverse Bits

[Swift]LeetCode190. 顛倒二進位制位 | Reverse Bits

Reverse bits of a given 32 bits unsigned integer.

Example 1:

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10101111110010110010011101101001.

Note:

  • Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer -1073741825.

Follow up:

If this function is called many times, how would you optimize it?


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

示例 1:

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

示例 2:

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

提示:

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

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


amazing

 1 class Solution {
 2     func reverseBits(_ n: UInt32) -> UInt32 {
 3         var n = n
 4         n = (n >> 16) | (n << 16);
 5         n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
 6         n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
 7         n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
 8         n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
 9         return n;
10     }
11 }

normal

 1 class Solution {
 2     func reverseBits(_ n: UInt32) -> UInt32 {
 3         var res: UInt32 = 0
 4         for i in 0..<32
 5         {
 6             res = (res << 1) + (n >> i & 1)
 7         }
 8         return res
 9     }
10 }