Skip to content

Commit be0ba09

Browse files
committed
Added reverse bits
1 parent e0ba87a commit be0ba09

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Easy/ReverseBits.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.*;
2+
3+
/**
4+
* Reverse bits of a given 32 bits <strong>unsigned</strong> integer.
5+
*
6+
* Example:
7+
* input 43261596, represented in binary as 00000010100101000001111010011100
8+
* return 964176192, represented in binary as 00111001011110000010100101000000
9+
*
10+
* Follow up:
11+
* If this function is <strong>called many times</strong>, how would you
12+
* optimize it?
13+
*
14+
* Related problem: Reverse Integer
15+
*
16+
* Tags: Bit Manipulation
17+
*/
18+
class ReverseBits {
19+
public static void main(String[] args) {
20+
ReverseBits r = new ReverseBits();
21+
int a = 43261596;
22+
System.out.println(r.reverseBits(a));
23+
}
24+
25+
/**
26+
* O(1) Time, O(1) Space
27+
* Move res 1 bit left, a
28+
* Get first bit of n, b
29+
* res = a ^ b
30+
* Move n right 1 bit for next loop
31+
* Unsigned shift means fill new bit at the left with 0 instead of 1
32+
*/
33+
public int reverseBits(int n) {
34+
int res = 0;
35+
for (int i = 0; i < 32; i++) {
36+
res = (res << 1) ^ (n & 1); // add first bit of n to last bit of res
37+
n >>>= 1; // unsigned shift to right
38+
}
39+
return res;
40+
}
41+
}

0 commit comments

Comments
 (0)