Skip to content

Commit 35f9e27

Browse files
committed
Added reverse bits optimized
1 parent be0ba09 commit 35f9e27

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

Easy/ReverseBits.java

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,23 @@
1111
* If this function is <strong>called many times</strong>, how would you
1212
* optimize it?
1313
*
14+
* Answer:
15+
* Cache result for each bytes.
16+
*
1417
* Related problem: Reverse Integer
1518
*
1619
* Tags: Bit Manipulation
1720
*/
1821
class ReverseBits {
1922
public static void main(String[] args) {
2023
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));
2331
}
2432

2533
/**
@@ -38,4 +46,33 @@ public int reverseBits(int n) {
3846
}
3947
return res;
4048
}
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+
}
4178
}

0 commit comments

Comments
 (0)