# 2ms Java solution

• ``````public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int rlt = 0;

for(int i = 32 ; i > 0 ; i--){
rlt += (((n<<(i-1))>>>31)<<(i-1));
}

return rlt;
}
}``````

• public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int temp = 0;
int result = 0;
int array[] = new int[32];
int i = 0;
for ( i = 0; i < 32; i++){
temp = n % 2;
n = n / 2;
temp = (temp) <<(31 - i);
result = result + temp;
}

``````    return result;
}
``````

}
anyone can help me why this not correct

• The problem is at "n = n / 2;". It does not treat n as an unsigned value. It works to use "n = n >>> 1;".

• @wei130
Your code can be accepted if modified as below:

``````public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int temp = 0;
int result = 0;
int array[] = new int[32];
int i = 0;

for ( i = 0; i < 32; i++) {
temp = n % 2;
n = n >>> 1;
temp = (temp) << (31 - i);
result = result + temp;
}

return result;
}
}``````

• Very smart solution.

• Thank you. :)

• this line is useless:
int array[] = new int[32];

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