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

Is the Reverse Bits Solution Using Left Shift Results correct

尝试使用左移结果解决反向位解决方案,问题说 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 最后 return 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 而不是移位运算符来避免这种情况。

没问题,但是:

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

  • 最后,以二进制形式输出return值可能会有用,这样您可以更轻松地验证结果。

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