LeetCode 190: Reverse Bits Solution

Master LeetCode problem 190 (Reverse Bits), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

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. :

Solution Code

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 190 (Reverse Bits)?

This page provides optimized solutions for LeetCode problem 190 (Reverse Bits) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 190 (Reverse Bits)?

The time complexity for LeetCode 190 (Reverse Bits) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 190 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 190 in Java, C++, or Python.

Back to LeetCode Solutions