Fizz Buzz: Software engineering interview question
Thursday, May 31st, 2007Having never heard of this before, it came as a shock. Its so simple that seems almost like a trick but its really not. I actually do like the question for that reason. Sometimes in the real world solutions are that simple as its a good trait to be able to recognize it. I answered the question well (or so I think), but I didnt pick up the simple refactor. If I was coding in front a computer I would have seen it in about 5 minutes but its different when you’re on a whiteboard in front of two senior architects. So heres the question:
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”.
So here’s what I came up with (in pseduo code):
for ( int i = 1 ; i <= 100; i ++ ) {
if (i % 15 == 0 ) print "FizzBuzz";
elseif (i % 3 == 0 ) print "Fizz";
elseif (i % 5 == 0 ) print "Buzz";
else print i;
}
So? Do you see it? Do you see the ‘refactor’ if it were (ignoring the ugly switch, design patterns, or thread safety for that matter)? Although the change is small change it does make a difference. Keep in mind this is pseudo code but they wanted me to see that if I cant print “Fizz” and “Buzz” in two separate ‘if’ blocks.
for ( int i = 1 ; i <= 100; i ++ ) {
if (i % 3 == 0 ) print "Fizz";
if (i % 5 == 0 ) print "Buzz";
otherwise print i;
}
This is now one of my favorite books on Java which I am probably going to read again just to be sure I have soaked up as much information as I can. This is a practical book written by a practical person who understands his audience, engineers. He is straight to the point with his code examples and doesnt bore you to death explaining every little detail or referencing lines of code and functions 8 pages back. I wish more technical writers would be this concise and straight to the point. There is something to be said for any technical writer who can get their message across with fewer words. No where else can I think of a better example of the old adage “less is more”. I would highly recommend this book to any engineer, especially associates.


