Optimal FizzBuzz JAVA Code - Java Interview Question

The FizzBuzz program question is a very commonly asked question in Java Interviews, if you have not come across this question, trust me, you will soon.

The rules of FizzBuzz are as follows:

For numbers 1 through n,

if the number is divisible by 3 print Fizz;
if the number is divisible by 5 print Buzz;
if the number is divisible by 3 and 5 (15) print FizzBuzz;
else, print the number itself.

This looks to be a simple one and is a simple one to write a program for, but then, the objective is to filter out a bad programmer from a normal or a good programmer.

An instance of bad programming is,

for (int i = 1; i <= num; i++) {
   if (i % 3 == 0) {
    System.out.println("Fizz");
   } else if (i % 5 == 0) {
    System.out.println("Buzz");
   } else if (i % 15 == 0) {
    System.out.println("FizzBuzz");
   } else {
    System.out.println(i);
   }
  }

Now, there are two things which are really bad here,

  1. You are not aware of how an if/else works. If you still don't get why I mentioned this, well. Since, 15 has factors, 3 and 5. The third if condition will never be executed and hence it won't print FizzBuzz even if the number is 15 or multiples of 15.
  2. Using System.out.println in every if/else wastes hell lot of time.


One of the optimal solution to this question is,

public class FizzBuzz {

 public static void main(String[] args) {
  int num = 100;
  fizzBuzzSB(num);
 }

 private static void fizzBuzzSB(int num) {
  long t1 = System.currentTimeMillis();
  
  StringBuilder sb = new StringBuilder(num);
  for (int i = 1; i <= num; i++) {
   if (i % 15 == 0) {
    sb.append("FizzBuzz\n");
   } else if (i % 3 == 0) {
    sb.append("Fizz\n");
   } else if (i % 5 == 0) {
    sb.append("Buzz\n");
   } else {
    sb.append(i+"\n");
   }
  }
  System.out.println(sb);

  System.out.println("time taken with SB: "+ (System.currentTimeMillis() - t1));
 }
}

The time taken to run the FizzBuzzSB method where we used a StringBuffer, in my machine, was,  2ms against 16ms of the one where we used System.out.println against every if/else condition.

Know a better solution, comment below.

See you around.
Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
Connect with him on:
    Blogger
    Facebook

1 comments:

  1. This is very informative blog and nice article , I really like your technique of writing a blog. I book marked it to my bookmark site list and will be checking back in the near future Best Selenium Training in Chennai

    ReplyDelete