Java: Count the number of set bits in a 32-bit integer
Hamming Weight of Integer (Count Set Bits)
From Wikipedia,
The Hamming weight of a string is the number of symbols that are different from the zero-symbol of the alphabet used. It is thus equivalent to the Hamming distance from the all-zero string of the same length. For the most typical case, a string of bits, this is the number of 1's in the string, or the digit sum of the binary representation of a given number and the ℓ₁ norm of a bit vector. In this binary case, it is also called the population count, popcount, sideways sum, or bit summation.
Example:
String | Hamming weight |
---|---|
11101 | 4 |
11101000 | 4 |
00000000 | 0 |
789012340567 | 10 |
Sample Solution:
Java Code:
Sample Output:
Input a number: 1427 6
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to compute the Hamming weight of an integer using bitwise operations without iterating over all 32 bits.
- Write a Java program to calculate the Hamming weight of an integer recursively.
- Write a Java program to compare two different methods for computing the Hamming weight of a 32-bit integer and output their results.
- Write a Java program to count the number of set bits in a binary representation of an integer using a well-known bit manipulation trick.
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to check if each letter of a given word is less than the one before it.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.