Enter any decimal number as an input. After that we first convert the given decimal number into binary number and then check at every position for 1. If 1 occurs then we increase the counter by one. Hence at last we get the counter value as the output.
Here is the source code of the Java Program to Count the Number of Bits set to One. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class Count_One
public static void main(String args)
int n, m, count = 0;
String x = "";
Scanner s = new Scanner(System.in);
System.out.print("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')
System.out.println("No. of 1's are:"+count);
$ javac Count_One.java $ java Count_One Enter the Decimal Number:15 No. of 1's are:4
Sanfoundry Global Education & Learning Series - 1000 Java Programs.