Overview
Given a 32-bit unsigned integer n, reverse its bits and return the result as an unsigned integer.
For example, the 32-bit representation of 43261596 is 00000010100101000001111010011100. Reversing gives 00111001011110000010100101000000, which is 964176192.
Constraints
- Input is a 32-bit unsigned integer (
0 <= n <= 2^32 - 1). - Return a 32-bit unsigned integer.
- Use bitwise operations for an efficient solution.
Examples
reverseBits(43261596); // => 964176192 // Binary: 00000010100101000001111010011100 // Reversed: 00111001011110000010100101000000
reverseBits(0); // => 0 reverseBits(1); // => 2147483648 (1 followed by 31 zeros)
Solution
Reveal solution
function reverseBits(n) {
let result = 0;
for (let i = 0; i < 32; i++) {
result = (result * 2) + (n & 1);
n = Math.floor(n / 2);
}
return result;
}We avoid >>> and << issues with large JS numbers by using multiplication and division.
Resources
bit-reversal.js
Bit Reversal
easycodingAlgorithmsBit Manipulation
Overview
Given a 32-bit unsigned integer n, reverse its bits and return the result as an unsigned integer.
For example, the 32-bit representation of 43261596 is 00000010100101000001111010011100. Reversing gives 00111001011110000010100101000000, which is 964176192.
Constraints
- Input is a 32-bit unsigned integer (
0 <= n <= 2^32 - 1). - Return a 32-bit unsigned integer.
- Use bitwise operations for an efficient solution.
Examples
reverseBits(43261596); // => 964176192 // Binary: 00000010100101000001111010011100 // Reversed: 00111001011110000010100101000000
reverseBits(0); // => 0 reverseBits(1); // => 2147483648 (1 followed by 31 zeros)
Solution
Reveal solution
function reverseBits(n) {
let result = 0;
for (let i = 0; i < 32; i++) {
result = (result * 2) + (n & 1);
n = Math.floor(n / 2);
}
return result;
}We avoid >>> and << issues with large JS numbers by using multiplication and division.
Resources
NameTopicDifficulty
103 of 103 problems