Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
My code:
1 public class ReverseBits { 2 3 public static void main(String[] args) { 4 // TODO Auto-generated method stub 5 ReverseBits test = new ReverseBits(); 6 7 System.out.println(test.reverseBits(43261597)); 8 } 9 10 // Accepted 11 public long reverseBits(int n) { 12 13 String str = Integer.toBinaryString(n); 14 StringBuilder sb = new StringBuilder(); 15 int len = str.length(); 16 17 for(int i = len -1; i >=0 ; i--) 18 { 19 sb.append(str.charAt(i)); 20 } 21 for(int i = len; i < 32; i++) 22 { 23 sb.append("0"); 24 } 25 26 long base = 1; 27 long re = 0; 28 for(int i = 31 ; i >=0; i--) 29 { 30 if( sb.charAt(i) == '1') 31 { 32 re += base; 33 } 34 base *=2; 35 } 36 return re; 37 } 38 }