Back to all solutions
#191 - Number of 1 Bits
Problem Description
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Solution
/**
* @param {number} n - a positive integer
* @return {number}
*/
var hammingWeight = function(n) {
return n.toString(2).match(/1/g)?.length || 0;
};