less than 1 minute read

Problem

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"]

Example 3:

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

Constraints:

  • 1 <= n <= 10^4

Solution

Approach

  1. 배열 리스트를 선언한다.

  2. 문자 1부터 n까지 리스트에 추가하되 15로 나누어 질 수 있으면 “FizzBuzz”를 추가하고, 3으로 나누어 질 수 있으면 “Fizz”를 추가하고, 5로 나누어 질 수 있으면 “Buzz”를 추가한다.

  3. 리스트를 반환한다.

    Code

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

    Time Complexity

    • 정수 n이 주어졌을 때, 코드의 수행 시간을 좌우하는 것은 for반복문의 n번 계산 횟수이다. 따라서 본 솔루션은 O(n)의 시간 복잡도를 가진다.

Categories:

Updated:

Leave a comment