Fizz Buzz


Why ??? 

Well... Why not ?

Ok. I'll be honest this was my first time solving this problem and I bungled it. 

My original understanding of the problem had me simply converting an Integer to a String. I blew past the examples and the fact that the solution actually called for a list where each value in the array was determined by the index (1-indexed)

Here is a link the problem - https://leetcode.com/problems/fizz-buzz/

The solution requires -

  • iterating through all the values until n+1 (n is the input to this problem) and then 
  • using the modulo operator to determine if the number is divisible by 3 or 5 or both and 
  • appropriately appending the correct String.

Code

As stated above, the following Java code iterates through all the indexes and appends the String value to the list -

public String getValue(int n) {

    if (n % 3 == 0) {
        if (n % 5 == 0)
            return "FizzBuzz";
        else
            return "Fizz";
    } else if (n % 5 == 0)
        return "Buzz";

    return Integer.toString(n);
}

public List<String> fizzBuzz(int n) {

    List<String> ret = new ArrayList<>();

    for (int i = 1; i < n+1; i ++) {
        ret.add(getValue(i));
    }

    return ret;
}