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
(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
Post a Comment