Count Bits One via Integer.toBinaryString(n) method - Java Algorithm

Java examples for Algorithm:Number

Description

Count Bits One via Integer.toBinaryString(n) method

Demo Code

public class Main {
  public static void main(String[] args) {
    int n = 7;//from w w w.ja v  a2 s.co  m
    String nBin = String.format("%16s", Integer.toBinaryString(n)).replace(" ", "0");
    int counter = 0;
    for (int i = 0; i < nBin.length(); i++) {

      char temp = nBin.charAt(i);
      if (temp == '1') {
        counter++;
      }
    }// end of for

    System.out.println(nBin);
    System.out.println(counter);

  }// end of main
}// end of class

Related Tutorials