How to solve FizzBuzz in Java?

FizzBuzz is one of the most frequently asked questions on programming interviews and used to filter programmers who can't program. It looks extremely simple but it's tricky for those programmers or coder who struggle to structure their code. Fizzbuzz problem statement is very simple, write a program which return "fizz" if the number is a multiplier of 3, return "buzz" if its multiplier of 5 and return "fizzbuzz" if the number is divisible by both 3 and 5. If the number is not divisible by either 3 or 5 then it should just return the number itself. You can see nothing is fancy when it comes to thinking about the solution, but when you start coding, you will see a problem with structuring your code, particularly if else blocks.

In this article, we will go through a couple of solution to understand the crux of this problem. If you are learning Java 8, then you can also solve this problem using lambda expression and streams, as shown here.

Btw, If you are preparing for programming job interviews and looking for some coding problems to prepare well, then I will recommend you to go through problems given in the book, Cracking the Coding Interview. It contains around 150 programming questions and their solutions with a good explanation.


First solution of FizzBuzz Problem

Many programmers come up with the following solution when first faced with Fizzbuzz problem :
 public static String fizzBuzz(int number) {
        if (number % 3 == 0) {
            if (number % 5 == 0) {
                return "fizzbuzz";
            } else {
                return "fizz";
            }
        } else if (number % 5 == 0) {
            return "buzz";
        }
        return String.valueOf(number);
    }


If you look at this solution closely you will find that the structure of the if statements is not good, and there are two tests for the same condition i.e. two if block to check if the number is divisible by 5. The problem is the code is not good but you should give the benefit of the doubt to the programmer because even though a test of 5 is written twice they are in different branches, and only one of them will execute, but I agree the code is not clean.



Second solution of FizzBuzz

They key of coming with perfect solution is coming up with an approach to do the test for divisible by both 3 and 5 first. This brings more readability without duplication, as shown here
public static String fizzBuzz2(int number) {

        if (number % 15 == 0) {
            return "fizzbuzz";
        } else if (number % 5 == 0) {
            return "buzz";
        } else if (number % 3 == 0) {
            return "fizz";
        }
        return String.valueOf(number);
 }

You can see that it's much cleaner even though it is also doing the test twice, but it's more pleasing to the eye and straightforward.

How to solve FizzBuzz in Java with example


Java Program to solve FizzBuzzProblem

Here is our complete Java program which combines both approaches to solving the fizzbuzz problem. We also have some unit tests to verify our solution meets the problem statements.
import org.junit.Test;
import static org.junit.Assert.*;
/**
 * Java Program to solve FizzBuzz problem
 * 
 * @author WINDOWS 8
 *
 */
public class FizzBuzzTest {

    /**
     * Java Method to solve FizzBuzz problem, which states that program
     * should print fizz if number is multiple of 3, 
     * print buzz if number is multiple
     * of 5, and print fizzbuzz if number is multiple of both 3 and 5
     * 
     * @param number
     * @return
     */
    public static String fizzBuzz(int number) {

        if (number % 3 == 0) {
            if (number % 5 == 0) {
                return "fizzbuzz";
            } else {
                return "fizz";
            }
        } else if (number % 5 == 0) {
            return "buzz";
        }
        return String.valueOf(number);
    }

    /**
     * An improved version of earlier solution, much cleaner than previous
     * version because we have tested for divisible by 3 and 5 first.
     * It avoid duplication also.
     */
    public static String fizzBuzz2(int number) {
        if (number % 15 == 0) {
            return "fizzbuzz";
        } else if (number % 5 == 0) {
            return "buzz";
        } else if (number % 3 == 0) {
            return "fizz";
        }
        return String.valueOf(number);
    }
    
    
    @Test
    public void testFizzBuzz(){
        assertEquals("fizz", fizzBuzz(3));
        assertEquals("buzz", fizzBuzz(5));
        assertEquals("fizzbuzz", fizzBuzz(15));
        assertEquals("2", fizzBuzz(2));
    }
    
    @Test
    public void testFizzBuzzV2(){
        assertEquals("fizz", fizzBuzzV2(3));
        assertEquals("buzz", fizzBuzzV2(5));
        assertEquals("fizzbuzz", fizzBuzzV2(15));
        assertEquals("2", fizzBuzzV2(2));
    }
}

Test Result :
All Pass

That's all about how to solve FizzBuzz Problem in Java.  Sometime FizzBuzz is also asked as following problem statement, 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". So don't confuse there, same logic works fine.


Related Coding Problems from Programming Interviews
If you are a computer science graduate and serious about doing well on coding based questions on programming job interviews, try to solve following problems:
  • How to check if a given number is prime or not? (solution)
  • Write a program to print the highest frequency word from a text file? (solution)
  • How to find if given String is a palindrome in Java? (solution)
  • How to calculate factorial using recursion and iteration? (solution)
  • How to reverse an int variable in Java? (solution)
  • How to find the highest and lowest number from int array? (answer)
  • How do you swap two integers without using a temporary variable? (solution)
  • Top 10 Programming problems from Java Interviews? (article)
  • Write a program to check if a number is the power of two or not? (solution)
  • How to check if a year is a leap year in Java? (answer)
  • How to reverse String in Java without using StringBuffer? (solution)
  • Write code to implement Bubble sort algorithm in Java? (code)
  • How do you reverse word of a sentence in Java? (solution)
  • Write code to implement Quicksort algorithm in Java? (algorithm)
  • How to find a missing number in a sorted array? (solution)
  • Write a program to code insertion sort algorithm in Java (program)


Books for preparing Coding interviews
If you are not going Google, Microsoft or Amazon which ask very tough coding questions but preparing for all other software companies, following two books will help you more in short time:
  • Programming Interviews Exposed: Secrets to Landing Your Next Job (see here
  • Cracking the Coding Interview: 150 Programming Questions and Solutions (see here)

2 comments:

  1. Another possible solution is:

    public static String fizzBuzz3(int number) {
    StringBuilder sb = new StringBuilder();
    if (number % 3 == 0) {
    sb.append("fizz");
    }
    if (number % 5 == 0) {
    sb.append("buzz");
    }

    return sb.length() == 0 ? String.valueOf(number) : sb.toString();
    }

    BTW, you have compile error in testFizzBuzzV2 method.

    ReplyDelete
  2. Here is how to solve FizzBuzz in Java 8 using lambda expression and method references, awesome!!.

    ReplyDelete