190. Reversing binary bits
Answer:
- Loop 32 times, each time
n
Move one to the right, so that you can compare backwardsn
. - Compare each time
n
Is the first digit of alpha 1? If yes, you fill in the 1result
. - Each loop will
result
Move one to the left to achieve the willn
Upside down.
/ * * *@param {number} n - a positive integer
* @return {number} - a positive integer
*/
var reverseBits = function (n) {
let result = 0; // Store the result
// A 32-bit binary number, so it needs to be moved 32 times
// Move the last left bit of n to the first bit of result each time
for (let i = 0; i < 32; i++) {
// Move the result to the left one bit at a time, filling the space with the current number
If the move is placed after the if statement, it will result in one more move
result <<= 1;
// If the first position of n is 1, we need to fill 1 in result
if (n & 1) {
// If it is 1, you need to fill in 1
// If the value is 0, you do not need to fill it in
result += 1;
}
// move n one bit to the right to determine the next position
n >>= 1;
}
/ / 11111111111111111111111111111101, the Case after the inversion is negative, need is converted into a positive
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift
return result >>> 0;
};
Copy the code