Fizz Buzz

Fizz Buzz

Sergei Golitsyn

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

  • answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  • answer[i] == "Fizz" if i is divisible by 3.
  • answer[i] == "Buzz" if i is divisible by 5.
  • 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"]


Solution:

Let's think about the brut force

our first case is n % 3 == 0 and n % 5 == 0 --> FizzBuzz

second case is n % 5 == 0 --> Buzz

third case is n % 3 == 0 --> Fizz

But, how can we improve it?

We can add boolean variables isFizz and isBuzz and collect result string.

public List<String> fizzBuzz(int n) {
    List<String> rez = new ArrayList<>();
    for(int i = 1; i <= n; i++){
      boolean isThree = i % 3 == 0;
      boolean isFive = i % 5 == 0;
       
      String curStr = "";
       
      if(isThree){
        curStr += "Fizz";
      }
      if (isFive){
         curStr += "Buzz";
      }
      if(curStr.isEmpty()){
        curStr += String.valueOf(i);
      }
      rez.add(curStr);
    }
    return rez;
  } 



Report Page