Java - Count Bits One in an integer

Count Bits One in an integer

Description

Count Bits One in an integer

The input value is a decimal integer value, like 1,3,5,123.

The code should count the 1 in its binary form.

For example, decimal value 1, its binary form is 1, and there is only one 1 in its binary form.

For decimal 7, its binary form is 111, the count of 1 is 3.

Test cases

You can use the following test cases to verify your code logics.

ID Input Ouput
11 1
22 1
37 3
48 1

Code template

Cut and paste the following code snippet to start solve this problem.

public class Main {
  public static void main(String[] args) {
    test(1);
    test(2);
    test(7);
    test(8);
  }

  public static void test(int value) {
    //your code here
  }
}

Answer

Here is the answer to the question above.

Demo

public class Main {
  public static void main(String[] args) {
    test(1);/*ww w .j a  v a  2  s  .  c  o  m*/
    test(2);
    test(7);
    test(8);
  }

  public static void test(int value) {
    System.out.println("Input:" + value + " its binary:" + Integer.toBinaryString(value));

    int count = 0;
    while (value > 0) { // until all bits are zero
      if ((value & 1) == 1) // check lower bit
        count++;
      value >>= 1; // shift bits, removing lower bit
    }
    System.out.println("Cout of 1 in the binary:" + count);
  }
}

Related Quiz