Number of 1 Bits (Hamming Weight)
The "Number of 1 Bits" problem, also referred to as the Hamming weight calculation, is a common question in computer science that focuses on counting the number of 1 bits (set bits) in the binary representation of a number.
Problem Statement
Given a non-negative integer n, count and return the number of '1' bits (also known as set bits) in its binary representation.
JavaScript Solution
Here's a simple JavaScript function to solve this problem:
function hammingWeight(n) {
let count = 0;
while (n !== 0) {
count += n & 1;
n >>>= 1;
}
return count;
}
Breaking Down the Solution
-
Initialize a Count Variable: let count = 0; initializes a variable to keep track of the number of 1 bits.
-
Loop Until n is Zero: The loop while (n !== 0) {} continues until all bits of n have been checked.
-
Count 1 Bits: count += n & 1; adds 1 to count if the least significant bit of n is 1.
-
Right Shift n: n >>>= 1; performs a logical right shift on n, moving all bits to the right by one place. This step is crucial for checking the next bit in the next iteration.
-
Return the Count: After all bits have been checked, the function returns the count of 1 bits.
Conclusion
Calculating the Hamming weight of a number is a fundamental operation in bit manipulation. This problem not only tests basic understanding of bitwise operations but also serves as a foundation for more complex bit manipulation challenges.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.