Description

Reverse bits of a given 32 bits unsigned integer.

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 a signed integer type. They should not affect your implementation, as the integer’s internal binary representation 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.

Example 1:

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

Example 2:

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

Constraints:

  • The input must be a binary string of length 32

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

Submitted Code

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        result = 0
        binary_str = bin(n)[2:].zfill(32)   # 슬라이싱으로 맨 앞 '0b' 제거 후 32비트에 맞춰 0으로 채움

        for i in range(32):
            result += int(binary_str[i]) * (2 ** i)

        return result

Runtime: 19 ms | Beats 45.46%
Memory: 12.35 MB | Beats 75.31%

입력값 n이 0으로 시작하는 경우 int 타입으로 계산할 수 없기 때문에 bin() 함수를 사용해서 str으로 만들어야 했다. 그리고 zfill()로 앞에 0을 채워 32비트 길이로 맞췄다.

Other Solutions

1st

class Solution:
    def reverseBits(self, n: int) -> int:
        res = 0
        for i in range(32):
            res = res << 1       # Shift left (make space for new bit)
            res += (n & 1)       # Add the least significant bit of n to res
            n = n >> 1           # Shift n to the right
        return res

time complexity: 𝑂(32)
space complexity: 𝑂(1)

비트 연산자 <<>> 를 활용하면 앞의 ‘0b’를 처리하지 않아도 된다. 여기서는 & 연산자를 사용해서 가장 오른쪽 비트 하나를 추출했다(0일 경우 0 & 1은 0, 1일 경우 1 & 1은 1이되기 때문).

res = 0
n = 0b11011010 (218)

i        n        res    res << 1    n & 1      res(new)    
0    11011010      0         0         0         0 + 0    
1     1101101      0         0         1         0 + 1
2      110110      1         2         0         2 + 0           
3       11011      2         4         1         4 + 1
4        1101      5        10         1         10 + 1
5         110     11        22         0         22 + 0
6          11     22        44         1         44 + 1
7           1     45        90         1         90 + 1

res = 0b10110110 (91)

Leave a comment