This Node JS function takes input as signed 2's complement and any particular reason why it returns wrong number of '1' bits
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Here is function which should return the output as 31
whereas it returns 1
var hammingWeight = function(n) {
let count = 0;
while (n !== 0) {
n = n & (n - 1);
count ;
}
return count;
};
console.log(hammingWeight(11111111111111111111111111111101))
Here is console output
PS C:\VSB-PRO> node Fibo.js
1
any reason what could have gone wrong in the javascript code,your help is highly appreciated
Regards,
Carolyn
CodePudding user response:
When you call hammingWeight(101)
, you are not using the binary string 1012 (4 1 = 5), but the decimal number 10110 (one hundred and one). Try instead hammingWeight(0b101)
.