The comments on this Hacker News post generated a bunch of opinions on the ability for developers to solve a FizzBuzz problem. Specifically in a coding interview. I’ve never actually seen what the FizzBuzz problem was, so I had to look it up. In this blog post I solve FizzBuzz in C#.
The FizzBuzz problem is a challenge for a developer to write a method, in any language, to return different parts of the word FizzBuzz.
It goes like this:
- If a number is divisible by 3 or 5 => return FizzBuzz
- If a number is only divisible by 3 => return Fizz
- If a number is divisible by 5 => return Buzz
- If a number is not divisible by 3 or 5 => return the number
Over twenty years of programming experience and I’ve never come across question in an interview so I thought it would be fun to jump onto .Net Fiddle to give it a try. In this function you take any number and check if it can be divisible by 3 or 5. The trick to this function is to use the % mod
operator to check if a number is divisible by another number. The mod
operator will return a number if there is a remainder after division between the two supplied numbers. If the number returned after division using the mod
operator you will return zero – meaning there isn’t a remainder after division. This is what the function is all about. Here’s my FizzBuzz implementation I wrote this morning after reading the Hacker News post.
Simple FizzBuzz implementation in C#
public class Program
{
public static void Main()
{
int i = 0;
while(i <=100)
{
string fizzWord = GetFizz(i);
Console.WriteLine(fizzWord);
i = i + 1;
}
}
public static string GetFizz(int i)
{
if(i % 3 == 0 && i % 5==0)
{
return "FizzBuzz";
}
else if(i % 3 == 0)
{
return "Fizz";
}
else if(i % 5 == 0)
{
return "Buzz";
}
return i.ToString();
}
}