Trying to solve Reverse Bits Solution Using Left Shift Results ,problem says
Reverse bits of a given 32 bits unsigned integer.
Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Here in the solution code loops 32 times,then doing left shifting of result,and then if num & 1 is more than 0 i.e. its 1.then increment the result and also right shift nums by 1 or nums modulus 2 and then finally return the result
why the output coming as 0,any thoughts and updated solution for this code
let reverseBits = function(nums) {
let result = 0
for (let i = 1; i <= 32; i ) {
result <<= 1
if (nums & 1 > 0)
result
nums >>= 1
}
return result
}
console.log(reverseBits(11111111111111111111111111111101))
Output is shown as 0
PS C:\VSB-PRO> node Fibo.js
0
CodePudding user response:
Some issues:
The example value you pass as argument to your function, is not given in binary notation, but in decimal notation, so it is a different number than intended. Use the
0bprefix for literals in binary notation.When using the
<<operator (and=<<), JavaScript will interpret the 32nd bit as a sign bit. I suppose it is not intended to produce negative values, so avoid this by using a multiplication by 2 instead of the shift operator.
Not a problem, but:
The
>>operator will have a specific effect on numbers that have the 32nd bit set: that bit will be retained after the shift. As your script never inspects that bit, it is not a problem, but it would be more natural if 0 bits were shifted-in. For that you can use the>>>operator.Finally, it may be useful to output the return value in binary notation so you can more easily verify the result.
let reverseBits = function(nums) {
let result = 0;
for (let i = 1; i <= 32; i ) {
// use multiplication to avoid sign bit interpretation
result *= 2;
if (nums & 1 > 0)
result ;
nums >>>= 1;
}
return result;
}
// Express number in binary notation:
let n = 0b11111111111111111111111111111101;
let result = reverseBits(n);
// Display result in binary notation
console.log(result.toString(2));
