原题链接在这里:
题目:
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?题解:
新学了一种API, Integer.reverse()可以直接返回binary的reverse. 参考链接:
Method 2 res左移一位后加上n的最右一位digit.
Time Complexity: O(1). 一共左移了32位. Space O(1).
AC Java:
1 public class Solution { 2 // you need treat n as an unsigned value 3 public int reverseBits(int n) { 4 //Method 1 5 //return Integer.reverse(n); 6 7 //Method 2 8 int res = 0; 9 for(int i = 0; i<32; i++){10 res <<= 1;11 res += ((n>>i)&1);12 }13 return res;14 }15 }
Follow up 要求 this function is called many times.
把int 拆成 4个byte 分别reverse 反着加回去. 同时维护HashMap, key是byte, value是reverse 这个byte后的结果int.
若function 被call了很多次,那么大部分的byte都已经有了对应的reverse value存在HashMap中了。
AC Java:
1 public class Solution { 2 HashMaphm = new HashMap (); 3 4 public int reverseBits(int n) { 5 byte [] bytes = new byte[4]; 6 7 //convert int into bytes 8 for(int i = 0 ; i<4; i++){ 9 bytes[i] = (byte)((n>>>8*i) & 0xFF);10 }11 12 int res = 0;13 for(int i = 0; i<4; i++){14 res <<= 8;15 res += reverseByte(bytes[i]);16 }17 18 return res;19 }20 21 private int reverseByte(Byte b){22 if(hm.containsKey(b)){23 return hm.get(b);24 }25 26 int val = 0;27 for(int i = 0; i<8; i++){28 val <<= 1;29 val += ((b>>>i)&1);30 }31 hm.put(b, val);32 return val;33 }34 }
类似.