Friday, March 09, 2007

FizzBuzz Problem

This has been on digg recently and there was some talk about it recently at work.

If you are interviewing someone and need a programming question to ask, this is a good one. Any competent programmer should be able to give you a solution.
This puzzle is typically given to all levels of programming candidates (newbie to senior) during their interview. According to numerous people, only about 10% of the programmers can pass it (even the seniors). Can you? (hint… its actually not that hard if you figure out the key).

Problem:

Write a (substitute language here) 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”.
The problem is actually simple and has a simple strait forward solution, which is what makes it such a good question to ask.

A simple solution would be to setup a loop from 1 through 100, checking for numbers that are divisible by 3, 5, or both and printing the correct output.

Since taking the simple solution is boring, here's a python solution that I came up with that is only one line long.

print "\n".join([((num % 3 == 0) and (num % 5 == 0)) and 'FizzBuzz' or (num % 3 == 0) and 'Fizz' or (num % 5 == 0) and 'Buzz' or str(num) for num in range(1, 101)])

Anyway, if you think you have a cool solution post it here.

Dan

2 comments:

Anonymous said...

Not a cool solution but a straight forward Java one...


for(int x = 1; x < 100; x++)
{
System.out.print(x);
if(x % 3 == 0 && x % 5 == 0)
{
System.out.print(" Fizz Buzz");
}
else if(x % 3 == 0)
{
System.out.print(" Fizz");
}
else if(x % 5 == 0)
{
System.out.print(" Buzz");
}
System.out.println("");
}

Anonymous said...

for(int x = 1; x < 101; x++)
{
System.out.print(x);
if(x % 3 == 0 && x % 5 == 0)
{
System.out.print(" Fizz Buzz");
}
else if(x % 3 == 0)
{
System.out.print(" Fizz");
}
else if(x % 5 == 0)
{
System.out.print(" Buzz");
}
System.out.println("");
}

// Small mistake - loop needs to go from 1-101 in Java.