使用左移结果的反向位解决方案是否正确



问题称,试图使用左移结果解决反向位解决方案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.

在解决方案中,代码循环32次,然后对结果进行左移,然后如果num & 1大于0i.e. its 1,则对结果进行递增,并对shift nums by 1nums modulus 2进行右移,最后返回result

为什么输出为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))

输出显示为0

PS C:VSB-PRO> node Fibo.js
0

一些问题:

  • 作为函数参数传递的示例值不是用二进制表示法,而是用十进制表示法,因此它与预期的数字不同。对二进制表示法中的文字使用0b前缀。

  • 当使用<<运算符(和=<<(时,JavaScript将把32nd位解释为符号位。我想这不是为了产生负值,所以通过使用2的乘积而不是移位运算符来避免这种情况。

不是问题,但是:

  • >>运算符将对设置了32位的数字产生特定影响:该位将在移位后保留。由于您的脚本从不检查该位,所以这不是问题,但如果0位被移入,则会更自然。为此,您可以使用>>>运算符。

  • 最后,以二进制表示法输出返回值可能很有用,这样可以更容易地验证结果。

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));

最新更新