The FizzBuzz test

The FizzBuzz test is a fairly straightforward programming question that is (apparently) sometimes used during job interviews. The question goes like so:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

If it seems easy, that’s because it is. However, a quick Google search for “FizzBuzz test” will tell you stories from people in the field who’ve learned that a lot of programmers and computer science graduates have difficulties coming up with a solution when asked. Incredible! I wonder how they manage to do that…

Anyway, here’s a solution I came up with after a bit of puzzling. It incorporates bit shifting and some logical operators to encode each case. As you can see, I had to jump through some hoops because C# does not allow you to bit shift booleans and I didn’t want to convert anything.

static void Main(string[] args)
{
    for (int i = 1; i <= 100; i++)
    {
        var c = (((i % 3) << (2 - (i % 3)))) | ((i % 5) >> ((i % 5) / 2));
        switch (c)
        {
            case 0:
                Console.WriteLine("FizzBuzz");
                break;
            case 1:
                Console.WriteLine("Fizz");
                break;
            case 2:
                Console.WriteLine("Buzz");
                break;
            default:
                Console.WriteLine(i);
                break;
        }
    }
    Console.ReadKey();
}

I’m quite pleased with the result.