LeetCode 190: Reverse Bits

Problem Description

Explanation:

To reverse the bits of a 32-bit unsigned integer, we can iterate through each bit of the input integer from right to left (LSB to MSB) and construct the reversed integer by shifting the bits to the left and appending the current bit.

  1. Initialize a variable result to store the reversed bits.
  2. Iterate through each bit of the input integer from right to left.
  3. Check if the current bit is 1, then set the corresponding bit in the result by ORing with 1 shifted by the remaining iterations.
  4. Finally, return the result as the reversed integer.

Time Complexity: O(1) - Since we are iterating through a fixed number of bits (32 bits). Space Complexity: O(1) - Constant space is used. :

Solutions

public int reverseBits(int n) {
    int result = 0;
    for (int i = 0; i < 32; i++) {
        result = (result << 1) | (n & 1);
        n >>= 1;
    }
    return result;
}

Loading editor...