1 minute read

Problem

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?

Solution

Logic

  1. 정수 n과 1을 AND 비트 연산(&)을 수행하고 계산 결과를 반환을 위한 정수에 합산한다.

  2. 정수 n에 우측 쉬프트 비트 연산(»)을 수행하고, 반환을 위한 정수는 좌측 쉬프트 비트 연산(«)을 수행한다.

  3. 위 1, 2번 과정을 31(비트 자리 수 - 1)번 수행하고, 1번을 추가로 한 번 더 수행한다.

  4. 합산된 정수를 반환한다.

    Code

    public class Solution {
     // you need treat n as an unsigned value
     public int reverseBits(int n) {
         int res = 0;
         for (int i = 0; i < 32; i++) {
             res <<= 1;
             res += n & 1;
             n >>= 1;
         } return res;
     }
    }
    

    Explanation

    • 정수 n의 비트 자리 수를 n이라 가정할 때, 코드의 수행 시간을 좌우하는 것은 for반복문의 n번 계산 횟수이다. 따라서 본 솔루션은 O(n)의 시간 복잡도를 가진다.

Categories:

Updated:

Leave a comment