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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> #include <limits> #include <bitset> #include <cstdint> using namespace std; int main(int argc, char** argv) { using type = uint8_t; for(type number = 0; number < numeric_limits<type>::max(); ++number) { bool print = true; for(type shift = 0; shift <= numeric_limits<type>::digits - 2; ++shift) { static type mask = 0b11; if((number & (mask << shift)) == (mask << shift)) { print = false; break; } } if(print) cout << bitset<numeric_limits<type>::digits>(number) << endl; } return 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
.
This is a recursive solution to the problem.
Use code tag for inline and pre tag for blocks of code
[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!
We can solve it faster than that: https://pastebin.com/DWeq7LHR
Here’s a really fast solution: