Saturday, October 20, 2012

Mathematics3

Q3. How to count number of set bits in an integer?

Answer:
* Reducing an integer number by 1 always set the rightmost bit off. We can start reducing 1 till we get zero.

public class Mathematics3 {
    public static int counBits(int num) {
        if (num == 0)
            return 0;

        int count = 1;

        while ((num = (num & (num - 1))) != 0) {
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println("Number of 1 bits in 0 = " + counBits(0));
        System.out.println("Number of 1 bits in 1 = " + counBits(1));
        System.out.println("Number of 1 bits in 7 = " + counBits(7));
        System.out.println("Number of 1 bits in 15 = " + counBits(15));
        System.out.println("Number of 1 bits in 127 = " + counBits(127));
        System.out.println("Number of 1 bits in -1 = " + counBits(-1));
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.