# Share my solution. How to optimize it when this function is called many times?

• ``````private int[] reverseHex = new int[] {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};

// you need treat n as an unsigned value
public int reverseBits(int n) {
int rev = 0;
while (n != 0) {
rev = (rev << 4) + reverseHex[n & 0xF];
n >>>= 4;
}
return rev;
}
``````
1. Create an array that contains the reverse number of 0-15.
2. Divide the number into 8 parts, each part has 4 bits which can represent number 0-15. Get the reverse number of each part using the array.

• you should use for(int i = 0; i < 8; ++i) instead of while (n!=0). suppose n is 1, your while loop will be executed only 1 time.

• I noticed that also this passes:
public class Solution {
final static int[] reverseArr = {0,2,1,3};
// you need treat n as an unsigned value
public int reverseBits(int n) {
int r = 0;

``````    for(int i=0;i<16;i++) {
r = (r << 2) + reverseArr[n & 0x03];
n>>>=2;
}
return r;
}
``````

}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.