Leetcode: Reverse Bits
Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). Follow up: If this function is called many times, how would you optimize it? Related problem: Reverse Integer
Reverse Integer那道题会考虑溢出,因为那是reverse each digit,这里不会溢出,因为reverse的是each bit
1 public class Solution { 2 // you need treat n as an unsigned value 3 public int reverseBits(int n) { 4 int res = 0; 5 for (int i=0; i<32; i++) { 6 int bit = (n>>i) & 1; 7 res |= bit<<(31-i); 8 } 9 return res; 10 } 11 }
Q:如果该方法被大量调用,或者用于处理超大数据(Bulk data)时有什么优化方法?
A:这其实才是这道题的精髓,考察的大规模数据时算法最基本的优化方法。其实道理很简单,反复要用到的东西记下来就行了,所以我们用Map记录之前反转过的数字和结果。更好的优化方法是将其按照Byte分成4段存储,节省空间。参见这个帖子。How to optimize if this function is called multiple times? We can divide an int into 4 bytes, and reverse each byte then combine into an int. For each byte, we can use cache to improve performance.
1 // cache 2 private final Map<Byte, Integer> cache = new HashMap<Byte, Integer>(); 3 public int reverseBits(int n) { 4 byte[] bytes = new byte[4]; 5 for (int i = 0; i < 4; i++) // convert int into 4 bytes 6 bytes[i] = (byte)((n >>> 8*i) & 0xFF); 7 int result = 0; 8 for (int i = 0; i < 4; i++) { 9 result += reverseByte(bytes[i]); // reverse per byte 10 if (i < 3) 11 result <<= 8; 12 } 13 return result; 14 } 15 16 private int reverseByte(byte b) { 17 Integer value = cache.get(b); // first look up from cache 18 if (value != null) 19 return value; 20 value = 0; 21 // reverse by bit 22 for (int i = 0; i < 8; i++) { 23 value += ((b >>> i) & 1); 24 if (i < 7) 25 value <<= 1; 26 } 27 cache.put(b, value); 28 return value; 29 }