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