Advertisement
felix_de_suza

Count Of Bits One - Task

May 14th, 2014
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.65 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3.  
  4. public class CountOfbitsOne {
  5.  
  6.     public static void main(String[] args) {
  7.        
  8.         @SuppressWarnings("resource")
  9.         Scanner input = new Scanner(System.in);
  10.        
  11.         int a = input.nextInt();
  12.         int countBitsOne = 0;
  13.         int mask = 1;
  14.         String aBinaryString = String.format("%16s",Integer.toBinaryString(a)).replace(' ', '0');
  15.         int aBinaryInteger = Integer.parseInt(aBinaryString);
  16.        
  17.         for (int i = 0; i < aBinaryString.length(); i++) {
  18.             if (((mask << i) & aBinaryInteger) == 1) {
  19.                 countBitsOne ++;
  20.             }
  21.         }
  22.        
  23.         System.out.printf("%16s",aBinaryString);
  24.         System.out.println();
  25.         System.out.println(countBitsOne);
  26.  
  27.     }
  28.  
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement