FizzBuzz

Turn the numbers 1 to n into Fizz, Buzz, FizzBuzz or the number itself, using remainders after dividing by 3 and 5.

Given a whole number n, return a list of strings with one entry for each number i from 1 to n, in order. A number is divisible by 3 when 3 goes into it evenly, with nothing left over. The entry for i is:

Example 1
Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]
Example 2
Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Solution

The Idea

Picture FizzBuzz as a counting game for a group of players. They take turns counting up from 1, one number each. Instead of a number that 3 goes into evenly, a player says "Fizz", and instead of one that 5 goes into evenly, "Buzz". Here the program plays every turn and writes the answers into a list.

Follow Example 2 from the start. The numbers 1 and 2 stay as they are, 3 becomes Fizz, 4 stays, and 5 becomes Buzz. After that, 6, 9 and 12 are Fizz and 10 is Buzz. Then comes 15. Three goes into 15 five times and 5 goes into it three times, so 15 fits both rules. Which word should it get? The statement settles it: both words together, FizzBuzz.

How can a program tell whether 3 goes into a number evenly? It divides and looks at what is left over, called the remainder. Java's % operator gives it: 7 % 3 is 1, because 7 is two threes with 1 left over, while 9 % 3 is 0. A remainder of 0 means the number divides evenly. The picture lays out these remainders for Example 2.

The numbers 1 to 15, each with its remainder after dividing by 3 and after dividing by 5. A 0 in the first remainder row gives Fizz, a 0 in the second gives Buzz, and at 15 both are 0, so the output is FizzBuzz.

Each column is one number. The row labelled "remainder after ÷ 3" has a blue 0 under 3, 6, 9, 12 and 15, and those are the Fizz columns of the output row. The row labelled "remainder after ÷ 5" has a teal 0 under 5, 10 and 15, the Buzz columns. Column 15, framed in orange, has a 0 in both rows, and its output shows Fizz and Buzz together.

So every number falls into one of four cases: both remainders are 0, only the first is, only the second is, or neither is. The case to handle with care is the first one, because a number like 15 also passes each single test on its own.

Solution Approach

The code needs three decisions: the order of the tests, how to test for 3 and 5 at once, and how to put a plain number into a list of strings. Building each word from two pieces is an optional way that needs neither the careful order nor the test for 15.

Order of the tests

Which test should come first? The tests sit in an if-else if chain, where Java runs the first branch whose condition is true and skips the rest. If the test for 3 came first, 15 would pass it and get Fizz, and the FizzBuzz branch would never run.

So the "both" case goes first, followed by the tests for 3 and for 5. Once "both" is ruled out, a number can pass at most one of those two, so their order does not matter.

Testing for 3 and 5 at once

How do we test for both? Writing i % 3 == 0 && i % 5 == 0 works, and a shorter test is i % 15 == 0. A number that both 3 and 5 go into evenly has 3 and 5 among its factors. Since 3 and 5 have no common factor other than 1, such a number is a multiple of 3 × 5 = 15.

That shortcut needs the two numbers to share no factor. With 4 and 6, which share the factor 2, the number 12 is divisible by both, yet 4 × 6 = 24 does not go into it.

Numbers as text

What goes into the list for a number like 7? The list holds strings, so the number is turned into text with String.valueOf(i), which gives "7".

Optional: building each word from two pieces

Is there a way without a separate test for 15? Start each entry as an empty string, add "Fizz" when the remainder after dividing by 3 is 0, then add "Buzz" when the remainder after dividing by 5 is 0. For 15 both pieces get added, in that order, which spells FizzBuzz. If nothing was added, the entry is the number itself.

This version suits a game with more rules, such as a third word for multiples of 7, because each rule is one more line and no combined tests are needed. A run that compared both versions gave the same list for every n from 0 to 1000.

Java Solution

The method fizzBuzz works in these steps:

  1. First, create an empty ArrayList named answer to hold the entries.
  2. A for loop moves i from 1 up to n, including n itself.
  3. For each i, an if-else if chain tests i % 15 == 0 first and adds "FizzBuzz", then i % 3 == 0 for "Fizz", then i % 5 == 0 for "Buzz".
  4. When none of those three tests passes, the last branch adds String.valueOf(i), the number as text.
  5. After the loop, return answer.

The main method runs both examples, then n = 1 and n = 0, and finally n = 45, printing only the entries for 30 and 45, the next two multiples of 15.

Java
import java.util.ArrayList;
import java.util.List;

public class FizzBuzz {

    public static List<String> fizzBuzz(int n) {
        List<String> answer = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            if (i % 15 == 0) {
                answer.add("FizzBuzz");       // a multiple of 3 and of 5
            } else if (i % 3 == 0) {
                answer.add("Fizz");
            } else if (i % 5 == 0) {
                answer.add("Buzz");
            } else {
                answer.add(String.valueOf(i)); // the number itself, as text
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        System.out.println(fizzBuzz(5));
        System.out.println(fizzBuzz(15));
        System.out.println(fizzBuzz(1));
        System.out.println(fizzBuzz(0));
        List<String> upTo45 = fizzBuzz(45);
        System.out.println("30: " + upTo45.get(29) + ", 45: " + upTo45.get(44));
    }
}

Running it prints:

Output
[1, 2, Fizz, 4, Buzz]
[1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz]
[1]
[]
30: FizzBuzz, 45: FizzBuzz

Java prints a list of strings without quotes, so [1, 2, Fizz, 4, Buzz] on top is Example 1. The second line ends in FizzBuzz at 15, as in Example 2. With n = 1 the loop runs once and gives [1].

With n = 0 the condition i <= n is false from the start, so the loop never runs and the list stays empty: []. The last line shows FizzBuzz at 30 and at 45, so the test for 15 catches later multiples of 15 too, not only 15 itself.

What if the test for 3 came first in the chain? A run with the tests in the order 3, 5, 15 gives [11, Fizz, 13, 14, Fizz] for the numbers 11 to 15, and not a single FizzBuzz up to 45.

Complexity

Each number from 1 to n gets a few remainder tests and one entry in the list.

  • Time: O(n), because the loop runs once for each of the n numbers, and each pass does at most three remainder tests and one add to the list.
  • Space: O(n) for the answer, because the list holds one string per number, while the method itself keeps only the counter i.

Another short exercise built on remainders is Ugly Number, which asks whether a number's only prime factors are 2, 3 and 5.