Count set bits in an integer

 

Set bits is nothing but number of 1's in the binary representation of the given integer. Lets see simple example and program to count the no. of set bits in the given integer.


Count set bits


import java.util.Scanner;

public class CountSetBits {

 public static void main(String[] args) {
  
  Scanner s = new Scanner(System. in);
  String str = "";
  int n = s.nextInt();
  s.close();
  int count = 0;
        while(n > 0)
        {
            int a = n % 2;
            str = (a == 0) ? 0 + str : 1 + str;
            count += a;
            n = n / 2;
        }

        System.out.println("BINARY VALUE : "+str);
        System.out.println("SET BITS     : "+count);
 }
}


INPUT:
13

OUTPUT:


BINARY VALUE : 1101
SET BITS     : 3


No comments:
Write comments