Reverse bits of a given 32 bits unsigned integer.
LeetCode-190: Reverse bits of a given 32 bits unsigned integer.
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.
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.
Here is a java implementation:
public int reverseBits(int n) {
int res = 0;
for(int i=0; i < 32; i++){
// extract last bit
int bit = n & 1;
// shift result to left by 1 and add extracted bit
res = res << 1;
res+= bit;
// shift given integer to right by 1
n = n >> 1;
}
return res;
}
The time complexity for this approach is $O(1)$ as we are iterating over 32
bits of the given integer. The space complexity is also $O(1)$ as we are using only a constant amount of space to store res
and intermediate values.
Be notified of new posts. Subscribe to the RSS feed.