Java Program to Count the Number of Bits Set to One

In this Java program, we will have a glance at how to write a java program to count number of bits set to one.

Java Program to Count the Number of Bits Set to One

import java.util.Scanner;

public class Exp 

{

    public static void main(String[] args) 

    {

        int n, m, count = 0;

        String x = "";

        Scanner s = new Scanner(System.in);

        System.out.print("Please enter the Decimal Number:");

        n = s.nextInt();

        while(n > 0)

        {

            int a = n % 2;

            x = a + x;

            n = n / 2;

        }

        int l = x.length();

        for(int i = 0; i < l; i++)

        {

            if(x.charAt(i) == '1')

            {

                count++;

            }

        }

        System.out.println("No. of 1's are:"+count);

    }

}

Output: 

Please enter the Decimal Number:50

No. of 1's are:3

Leave a Comment

Your email address will not be published. Required fields are marked *