Fizz Buzz: Software engineering interview question
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
That IS progress. Your blogging skills are getting better and better. I had a great time reading this post.