Advertisement
GenuineSounds

Java Puzzler: Bits and Bobs

Dec 10th, 2015
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.84 KB | None | 0 0
  1. package com.genuinevm.puzzlers;
  2.  
  3. /**
  4.  * This puzzler is called Bits and Bobs, try and find out just by looking
  5.  * what the code will print.
  6.  *
  7.  * @author Brian Wiegand (GenuineSounds)
  8.  */
  9. public class BitsAndBobs {
  10.  
  11.     /**
  12.      * We need to find out the number of Bobs a given integer has.
  13.      * A Bob is a bit that is 1, but only if it isn't the sign bit.
  14.      */
  15.     public static void main(String[] args) {
  16.         int test = 53190; // 0b1100_1111_1100_0110
  17.         int bobs = numberOfBobs(test);
  18.         System.out.println("Number of Bobs: " + bobs);
  19.     }
  20.  
  21.     private static int numberOfBobs(int number) {
  22.         int out = 0;
  23.         for (int i = 0; i < 31; i++)
  24.             if (((number << i) & 1) == 1)
  25.                 out++;
  26.         return out;
  27.     }
  28. }
  29. /**
  30.  * Multiple Choice
  31.  *
  32.  * Number of Bobs:
  33.  *   A) 10
  34.  *   B) 11
  35.  *   C) 0
  36.  *   D) Throws exception
  37.  *
  38.  * Explain your answer.
  39.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement