Advertisement
nadiahristova

Prob7_CountOfBitsOne

Jan 24th, 2015
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.57 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Prob7_CountOfBitsOne {
  4.     public static void main(String[] args) {
  5.         Scanner input = new Scanner(System.in);
  6.        
  7.         System.out.print("Num = ");
  8.         int num = input.nextInt();
  9.         byte counter = 0;      
  10.         for (int i = 0; i < 16; i++) {
  11.             byte bit =(byte)((num >> i) & 1);          
  12.             if (bit == 1) {
  13.                 counter++;
  14.             }
  15.         }
  16.         //or we don't use a loop and we find the total count of 1s in num by doing this:
  17.         //byte counter = (byte)Integer.bitCount(num);
  18.         System.out.println("There are total " + counter + " ones in Num's binary form.");
  19.     }
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement