I dug up another one from years ago 🙂 This one asked to write a program that:

Prints all binary numbers that do not contain consecutive bits set.

My approach was to brute force over all possible numbers and test each one with a sliding 0b11 bit mask for 2 consecutive bits set.

The answer:

7 Replies to “Interview question, part 4”

  1. Your approach is reasonable, because the type can be chosen with so many bits that the listing would never finish in one’s lifetime, even if the computer could be expected to keep running that long.

    It’s also sufficiently efficient, because the main time consumer here is the i/o.

    However, it’s a bit more complex than strictly needed, because the check (for a value of unsigned type) can be reduced to

    (x & (x >>1)) == 0

    .

  2. [3ʳᵈ try, code formatting, + the right code; please delete posting attempts 1 and 2.]

    I think Vorbrodt’s approach of filtering is the most reasonable one since it’s so simple. Except as noted, the checking is really as simple as

    (x & (x >>1))

    . But for what it’s worth, here’s an iterative generative solution:

    Hopefully the code’s now presented correctly.

    Wish one could edit comments!

  3. Here’s a really fast solution:

Leave a Reply