Overview
Given a non-negative integer n, return the number of 1 bits in its binary representation (also known as the Hamming weight or popcount).
Constraints
0 <= n <= 2^31 - 1- Return a single integer.
Examples
hammingWeight(11); // => 3 // Binary: 1011 has three 1-bits
hammingWeight(128); // => 1 // Binary: 10000000 hammingWeight(0); // => 0
Solution
Reveal solution
function hammingWeight(n) {
let count = 0;
while (n > 0) {
count += n & 1;
n = n >>> 1;
}
return count;
}Each iteration checks the least significant bit and right-shifts. Using >>> 1 (unsigned right shift) avoids sign-extension issues.
Resources
count-set-bits.js
Count Set Bits in a Binary Number
easycodingAlgorithmsBit Manipulation
Overview
Given a non-negative integer n, return the number of 1 bits in its binary representation (also known as the Hamming weight or popcount).
Constraints
0 <= n <= 2^31 - 1- Return a single integer.
Examples
hammingWeight(11); // => 3 // Binary: 1011 has three 1-bits
hammingWeight(128); // => 1 // Binary: 10000000 hammingWeight(0); // => 0
Solution
Reveal solution
function hammingWeight(n) {
let count = 0;
while (n > 0) {
count += n & 1;
n = n >>> 1;
}
return count;
}Each iteration checks the least significant bit and right-shifts. Using >>> 1 (unsigned right shift) avoids sign-extension issues.
Resources
NameTopicDifficulty
103 of 103 problems