Advertisement
TzvetanIG

Count-of-Equal-Bit-Pairs

May 14th, 2014
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.87 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class _08_CountOfEqualBitPairs {
  4.  
  5.     public static void main(String[] args) {
  6.  
  7.         Scanner input = new Scanner(System.in);
  8.  
  9.         int number = input.nextInt();
  10.  
  11.         int count = 0;
  12.  
  13.         for (int i = 0; i < Integer.toBinaryString(number).length(); i++) {
  14.  
  15.             if (isFindPair(number, i, "11")) {
  16.                 count++;
  17.             }
  18.  
  19.             if (isFindPair(number, i, "00")) {
  20.                 count++;
  21.             }
  22.  
  23.         }
  24.  
  25.         System.out.println(count);
  26.     }
  27.  
  28.     public static boolean isFindPair(int number, int position, String bits) {
  29.  
  30.         if (number == 0) {
  31.             return false;
  32.         }
  33.  
  34.         boolean isFindPair = false;
  35.  
  36.         int bitsAsInt = Integer.parseInt(bits, 2);
  37.  
  38.         int shift = position;
  39.  
  40.         int mask = Integer.parseInt(bits.replace("0", "1"), 2);
  41.  
  42.         int lastBits = (number >> shift) & mask;
  43.  
  44.         if (bitsAsInt == lastBits) {
  45.             isFindPair = true;
  46.         }
  47.  
  48.         return isFindPair;
  49.     }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement