Fizz Buzz: Software engineering interview question

May 31, 2007
 by 

Having 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;
}


Categories: Computers


One Comment

  1. MopUpDuty says:

    That IS progress. Your blogging skills are getting better and better. I had a great time reading this post.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2005-2011 John Clarke Mills

Wordpress theme is open source and available on github.