Counts the number of bits set in an integer n. - Java Language Basics

Java examples for Language Basics:Bit

Description

Counts the number of bits set in an integer n.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int n = 2;
        System.out.println(countBits(n));
    }/*from  ww w. j ava  2 s  . c  o  m*/

    /**
     * Counts the number of bits set in an integer <i>n</i>.
     * 
     * @param n
     *            The integer to count.
     * @return The number of bits set in n.
     */
    public static int countBits(int n) {
        int total; // Holds the number of bits set.
        for (total = 0; n != 0; ++total) {
            n &= n - 1; // Clears the lowest bit that is set
        }
        return total;
    }
}

Related Tutorials