Monday, April 25, 2011

Java: count the number of one bits in an int

Integer.bitCount counts the number of one-bits in the two's complement binary representation of the specified int value. Example code:
public class CountOnes {
    public static void main(String[] args) {
 int[] i = { 1, 4, 7, 15 };
 for (int j = 0; j < i.length; j++) {
     System.out.printf("Number of 1's in %d: %d\n", i[j], Integer.bitCount(i[j]));
 }
    }
}

No comments:

Post a Comment

Chitika