How to count the number of 1 bit in a given number with Java

1 Answer

0 votes
public class MyClass {
    private static int Count1Bit(int n) {
        int count = 0;
        
        while (n > 0) {
            count += n & 1;
            n >>= 1;
        }
        return count;
    }
    public static void main(String args[]) {
        int n = 95; // 0101 1111
        
        int count = Count1Bit(n);
        
        System.out.println("Number of 1 bit = " + count);
    }
}




/*
run:
      
Number of 1 bit = 6
      
*/

 



answered Sep 13, 2021 by avibootz
edited Dec 4, 2021 by avibootz

Related questions

1 answer 179 views
2 answers 170 views
2 answers 152 views
1 answer 109 views
1 answer 122 views
...