Advertisement
dimipan80

Count of Bits One

Aug 17th, 2014
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.72 KB | None | 0 0
  1. /* Write a program to calculate the count of bits 1
  2.  * in the binary representation of given integer number n. */
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class _07_CountOfBitsOne {
  7.  
  8.     public static void main(String[] args) {
  9.         // TODO Auto-generated method stub
  10.         Scanner scan = new Scanner(System.in);
  11.         System.out.print("Enter a Integer number: ");
  12.         int number = scan.nextInt();
  13.  
  14.         // Short variant:
  15.         // int bitsCounter = Integer.bitCount(number);
  16.  
  17.         // Other simple variant:
  18.         int bitsCounter = 0;
  19.         while (number != 0) {
  20.             int bitValue = number & 1;
  21.             if (bitValue > 0) {
  22.                 bitsCounter++;
  23.             }
  24.  
  25.             number >>>= 1;
  26.         }
  27.  
  28.         System.out.println("The Count of bits 1 in that number is: " + bitsCounter);
  29.     }
  30.  
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement