Fizzbuzz – You better hope you can whiteboard this one!
You walk into your first programming interview ready to write some code. The manager sits you down, and says “John, have you ever heard of whiteboarding? I want you to solve fizzbuzz for me… You’ve heard of that right?” This is it. Your moment to shine. And then you step up to the whiteboard, and thankfully, you read this article and know just the trick to solving it efficiently!
The FizzBuzz problem sounds pretty simple, and only requires the programmer in the interview to think it through. The problem looks like this:
Print out the numbers 1 through 100. But for every number that is divisible by 3, print out fizz; If the number is divisible by 5, print out buzz; IF divisible by both 3 and 5, print out FizzBuzz.
As for any programming problem, there are multiple ways of approaching it. For this example, I am going to stick with the simplest approach so no matter what language you like to code in, you can solve it. No fancy libraries, method calls, etc. As is the case with many of these types of problems, it sounds difficult unless you know the “magic trick”. In FizzBuzz, it is very important to have an understanding of what the modulus operator is. If you don’t, you can read about it on wikipedia or just search for it on google. The basic idea is that when used, the modulus (or modulo) operator returns the remainder after dividing two operands (it looks like “%”). So
10 % 5 would return 0, since the numbers divide evenly. With that in your toolkit, let’s start solving this common programming problem!
Let’s Get to Work!
The first thing we need is our method/function structure (I’m using c#, use whatever language you want):
So now we know how the modulus operator works, so how can we apply that to this problem? To demonstrate let’s write it out in pseudo-code:
Loop through the numbers 1 through 100... If i divides evenly into both 3 and 5, print fizzbuzz else if it divides evenly into 5, print buzz else if it divides evenly into 3, print fizz else print n
The order of that if else if matters, because if we didn’t check if the number goes into both first,it would print one thing, and exit the if block… What i mean by that is the code below would see that the number goes into 5, and would then print buzz and exit the if else if block therefore NEVER testing our other scenarios!!!
Loop through the numbers 1 through 100 if i divides evenly into 5, print buzz else if it divides evenly into 3, print fizz else if n divides evenly into both 3 and 5, print fizzbuzz else print n
So lets actually convert this into code and test it!
And we did it! Solved that with no issues I hope… So now you know how to solve FizzBuzz, and how to use the modulo (or modulus) operator!