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:
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.
Rust Solution
Rust's mut n: u32 binding is required to shift n in place — parameters are immutable by default, so without mut the n >>= 1 reassignment wouldn't compile. The (n & 1) as i32 cast is mandatory because n & 1 is a u32 while count is inferred as i32 from the -> i32 return type, and Rust never converts between integer types implicitly. Since n is u32 (unsigned), >>= 1 is already a logical shift, so there's no need for JS's separate >>> operator. The bare count on the final line is the function's implicit return — no return keyword.
Go Solution
Go's for is the only loop keyword — with just a condition, for n != 0 is exactly a while loop. The count := 0 short declaration infers int, and int(n & 1) is a required explicit conversion because n & 1 is a uint32 while count is an int, and Go never mixes integer types implicitly. Since n is uint32 (unsigned), >>= 1 is already a logical shift, so JS's separate >>> operator isn't needed here.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.