11
11
* If this function is <strong>called many times</strong>, how would you
12
12
* optimize it?
13
13
*
14
+ * Answer:
15
+ * Cache result for each bytes.
16
+ *
14
17
* Related problem: Reverse Integer
15
18
*
16
19
* Tags: Bit Manipulation
17
20
*/
18
21
class ReverseBits {
19
22
public static void main (String [] args ) {
20
23
ReverseBits r = new ReverseBits ();
21
- int a = 43261596 ;
22
- System .out .println (r .reverseBits (a ));
24
+ // int a = 43261596;
25
+ // System.out.println(r.reverseBits(a));
26
+ // System.out.println(r.reverseBitsOpt(a));
27
+
28
+ int b = 1 ;
29
+ // System.out.println(r.reverseBits(b));
30
+ System .out .println (r .reverseBitsOpt (b ));
23
31
}
24
32
25
33
/**
@@ -38,4 +46,33 @@ public int reverseBits(int n) {
38
46
}
39
47
return res ;
40
48
}
49
+
50
+ private Map <Byte , Integer > cache = new HashMap <Byte , Integer >();
51
+
52
+ /**
53
+ * O(1) Time, O(1) Space
54
+ * Divide 32 bits into 4 bytes
55
+ * Cache each byte and its reversed result in a hashmap
56
+ * Check cache for result first instead of computing all
57
+ */
58
+ public int reverseBitsOpt (int n ) {
59
+ byte [] bytes = new byte [4 ];
60
+ for (int i = 0 ; i < 4 ; i ++)
61
+ bytes [i ] = (byte )((n >>> 8 * i ) & 0xFF );
62
+
63
+ int res = 0 ;
64
+ for (int i = 0 ; i < 4 ; i ++)
65
+ res = (res << 8 ) ^ reverseBytes (bytes [i ]);
66
+ return res ;
67
+ }
68
+
69
+ public int reverseBytes (byte b ) {
70
+ if (cache .containsKey (b )) return cache .get (b );
71
+ int res = 0 ;
72
+ for (int i = 0 ; i < 8 ; i ++) {
73
+ res = (res << 1 ) ^ ((b >>> i ) & 1 );
74
+ }
75
+ cache .put (b , res );
76
+ return res ;
77
+ }
41
78
}
0 commit comments