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”.

Tuesday, January 3, 2012

#1 - Common But Boring

Over the next year or so I intend on blogging 100 solutions to the FizzBuzz problem.  Each solution will vary in either technique or language, sometimes both.  The various "FizzBuzz" posts will also have various themes based on where the number lands.  The "number" days will simply be a solution with the prose around it focusing on the solution itself.

To start things off I thought it was best to focus on one of the more common answers.  This solution will be written in Java, which as of this writing was the #1 language on the TIOBE index in December of 2011.  This is merely evidence that it one of the most common languages.

public class FizzBuzz01 {
 public static void main(String[] args) {
  for (int i = 1; i <= 100; i++) {
   if ((i % 3 == 0) && (i % 5 == 0)) {
    System.out.println("FizzBuzz");
   } else if (i % 5 == 0) {
    System.out.println("Buzz");
   } else if (i % 3 == 0) {
    System.out.println("Fizz");
   } else {
    System.out.println(i);
   }
  }
 }
}

This is not a perfectly straightforward translation of the problem statement into a solution.  Without a lot of preparatory code you cannot directly translate the problem statement into code in the order it is presented in the problem statement.

This sample is about as simple as it can be done in Java. The only portion worth commenting on is how it transcribes the solution. Rather than going in the order the clauses are stated in the problem statement we consider the conditions from the last one first.  This changes it from a set of  "except" statements into a series of simpler if-then-else statements.

This is of the more common solutions (only considering correct solutions) presented by job candidates when asked this question in a job interview.  It is also one of the most boring solutions.

No comments:

Post a Comment