Reverse Bits - The Coding Shala

Home >> Programming >> Reverse Bits

 In this post, we will learn how to Reverse Bits and will implement its solution in Java.

Reverse Bits Problem

Reverse bits of a given 32 bits unsigned integer.

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)

Reverse Bits Java Solution

Approach 1

We will reverse bit by using shift operation. Will do this in two steps.

Step 1: Find the current bit.
Step 2: Set it to the 31-i position. [i is from 0 to 31].

Time Complexity: O(1). (loop will execute 32 times only)
Space Complexity: O(1).

Java Program: 

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int ans = 0;
        for(int i=0; i<32; i++) {
            //get the bit
            int bit = (n >> i) & 1;
            //set its position
            ans = ans | (bit << (31-i));
        }
        return ans;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

InterviewBit - Colorful Number Solution - The Coding Shala