Reverse Bits - The Coding Shala
Home >> Programming >> Reverse Bits
Other Posts You May Like
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).
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; } }
- LeetCode - Single Number
- Find XOR from 1 to n Numbers
- Maximum Absolute Difference
- LeetCode - Swap Nodes in Pairs
- Simple XML Validator
Comments
Post a Comment