Mirror Bits
Description
Reverse the order of the bits in a given integer.
Example
-
For
a = 97
, the output should bemirrorBits(a) = 67
.97
equals to1100001
in binary, which is1000011
after mirroring, and that is67
in base10
. -
For
a = 8
, the output should bemirrorBits(a) = 1
.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] integer a
Guaranteed constraints:
5 \leq a \leq 10^5
. -
[output] integer
[JavaScript (ES6)] Syntax Tips
1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Solution
1
2
3
4
5
6
7
8
9
function mirrorBits(a) {
var ret = 0;
var m = Math.floor(Math.log2(a));
var i = m + 1;
while (i--) {
ret = ret | (((a & (1 << i)) >> i) << (m - i));
}
return ret;
}