Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,111 questions

40,781 answers

573 users

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 54 views
2 answers 60 views
2 answers 62 views
...