File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments