Count set bits in an integer

Problem Link

(n-1) flips all bits till it sees a rightmost bit as 1 . It flips also the rightmost 1.

Hence, n-1 flips set bits one by one, when placed in a loop.

Code:

package bitManipulation;

public class CountSetBits {
   
    public static void main(String[] args){
        int n = 6, count = 0;
       
        while (n != 0){
            count +=1;
            n = n & (n-1);
        }
       
        System.out.println(count);
   
    }

}


Output:

2

Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Second Largest Element

Check if a number is a power of another number