Java Integer bitCount() method


The java.lang.Integer.bitCount() method returns the number of one-bits in the two's complement binary representation of the specified int value.

At first, set an int value −

int val = 210;

Now, find the number of one-bits −

Integer.bitCount(val)

Following is an example to implement the bitCount() method in Java −

Example

public class Main {
   public static void main(String[] args) {
      int val = 210;
      System.out.println("Number = " + val);
      System.out.println("Binary = " + Integer.toBinaryString(val));
      // returns the number of one-bits
      System.out.println("Number of one bits = " + Integer.bitCount(val));
   }
}

Output

Number = 210
Binary = 11010010
Number of one bits = 4

Updated on: 20-Sep-2019

107 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements