采用无符号整数和 returns 错误数量的“1”位的节点 JS 函数

Node JS function that takes an unsigned integer and returns wrong number of '1' bits

此 Node JS 函数将输入作为带符号的 2 的补码以及它 return错误的“1”位数的任何特定原因 Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

这里的函数应该 return output as 31 而它 returns 1

            var hammingWeight = function(n) {
                let count = 0;
                while (n !== 0) {
                  n = n & (n - 1);
                  count++;
                }
              
                return count;
              };

            console.log(hammingWeight(11111111111111111111111111111101))

这是控制台输出

            PS C:\VSB-PRO> node Fibo.js
            1

任何可能在 javascript 代码中出错的原因,非常感谢您的帮助

此致,

卡罗琳

当您调用 hammingWeight(101) 时,您没有使用 二进制字符串 1012 (4+1 = 5) ,而是十进制数 10110 (one hundred and one)。试试 hammingWeight(0b101).