Advertisement
dimipan80

C#Exams 5. Friend Bits (on Java Code)

Aug 26th, 2014
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class _5_FriendBits {
  4.  
  5.     public static void main(String[] args) {
  6.         // TODO Auto-generated method stub
  7.         Scanner scan = new Scanner(System.in);
  8.         long number = scan.nextLong();
  9.  
  10.         long friendBits = 0;
  11.         long aloneBits = 0;
  12.         if (number == 0 || number == 1) {
  13.             aloneBits = number;
  14.         } else {
  15.             int startBit = getMostLeftBitPositionInTheNumber(number);
  16.             long bitValue, previousBit, nextBit;
  17.             for (int bitPos = startBit; bitPos >= 0; bitPos--) {
  18.                 previousBit = (number >>> (bitPos + 1)) & 1;
  19.                 bitValue = (number >>> bitPos) & 1;
  20.                 nextBit = (number >>> (bitPos - 1)) & 1;
  21.                 if ((bitPos < startBit && bitValue == previousBit)
  22.                         || (bitPos > 0 && bitValue == nextBit)) {
  23.                     friendBits <<= 1;
  24.                     friendBits |= bitValue;
  25.                 } else {
  26.                     aloneBits <<= 1;
  27.                     aloneBits |= bitValue;
  28.                 }
  29.             }
  30.         }
  31.  
  32.         System.out.println(friendBits);
  33.         System.out.println(aloneBits);
  34.     }
  35.  
  36.     private static int getMostLeftBitPositionInTheNumber(long number) {
  37.         // TODO Auto-generated method stub
  38.         for (int i = 31; i > 0; i--) {
  39.             long bitValue = ((1 << i) & number);
  40.             if (bitValue > 0) {
  41.                 return i;
  42.             }
  43.         }
  44.         return 0;
  45.     }
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement