GenuineSounds icon

Java Puzzler: Bits and Bobs

GenuineSounds | PRO | 12/10/15 05:48:43 PM UTC | 0 ⭐ | 499 👁️ | Never ⏰ | []
Java |

840 B

|

None

|

0 👍

/

0 👎

package com.genuinevm.puzzlers;
 
/**
 * This puzzler is called Bits and Bobs, try and find out just by looking
 * what the code will print.
 * 
 * @author Brian Wiegand (GenuineSounds)
 */
public class BitsAndBobs {
 
    /**
     * We need to find out the number of Bobs a given integer has.
     * A Bob is a bit that is 1, but only if it isn't the sign bit.
     */
    public static void main(String[] args) {
        int test = 53190; // 0b1100_1111_1100_0110
        int bobs = numberOfBobs(test);
        System.out.println("Number of Bobs: " + bobs);
    }
 
    private static int numberOfBobs(int number) {
        int out = 0;
        for (int i = 0; i < 31; i++)
            if (((number << i) & 1) == 1)
                out++;
        return out;
    }
}
/**
 * Multiple Choice
 * 
 * Number of Bobs:
 *   A) 10
 *   B) 11
 *   C) 0
 *   D) Throws exception
 * 
 * Explain your answer.
 */

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎