Fizz Buzz (LeetCode #412)
Alex Sikorski

Alex Sikorski

Jul 08, 2022

Fizz Buzz (LeetCode #412)

#leetcode easy

#leetcode

#java

The problem can be found here.

Given an integer n, return a string array answer (1-indexed) where:

  1. answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  2. answer[i] == "Fizz" if i is divisible by 3.
  3. answer[i] == "Buzz" if i is divisible by 5.
  4. answer[i] == i (as a string) if none of the above conditions are true.

Example 1:

Input: n = 3
Output: ["1","2","Fizz"]

Example 2:

Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]

Example 3:

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

Constraints:

  1. 1 <= n <= 10^4

Initial Thoughts

The method return type is a List<String> so we can use an ArrayList<String> and add to it. It's clear to me from the start we will have to make use of the modulo operator to find out if a number is divisible by 3,5 or 3 and 5.

Solution

class Solution {
    public List<String> fizzBuzz(int n) {
        
        ArrayList<String> result = new ArrayList<>();
        
        for(int i = 1; i < n + 1; i++){
            if(i % 3 == 0 && i % 5 == 0) result.add("FizzBuzz");
            else if(i % 3 == 0) result.add("Fizz");
            else if (i % 5 == 0) result.add("Buzz");
            else result.add(String.valueOf(i));
        }
        
        return result;
    }
}

To summarise, we iterate from 1 to n with a for loop, and for every number we check if i modulo 3, 5 or 3 and 5 is 0. If it is 0, it means that i is divisible by that number, since the remainder is 0. In our if statements, we simply add the desired String to the result and once done iterating up to n + 1, we return the ArrayList.

Result

2022-07-08 09_47_42-Fizz Buzz - LeetCode — Mozilla Firefox.png

Alex Sikorski

Alex Sikorski

Currently working as a full stack Software Engineer and curiously seeking new knowledge in free time.

Leave a comment

Categories