알고리즘/해결

LeetCode412. Fizz Buzz

언클린 2020. 4. 12. 09:38
728x90

1. 문제(원본)

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

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

2. 문제

3으로 나뉘어 지면 Fizz 5로 나뉘어 지면 Buzz 둘 다 나뉘어 지면 FizzBuzz를 출력하라

3. 나의 답

class Solution {

    func fizzBuzz(_ n: Int) -> [String] {

        guard n > 0 else {

            return []

        }

        var result: [String] = []

        for element in 1...n {

            var data = String(element)

            if element % 3 == 0 {

                data = "Fizz"

            }

            if element % 5 == 0 {

                if data.contains("Fizz") { data += "Buzz" } else { data = "Buzz" }

            }

            result.append(data)

        }

        return result

    }

}

4. 다른 유저의 답

#1

func fizzBuzz(_ n: Int) -> [String] {

 var output = [String]()

    for i in 0..<n{

        var index = i + 1

        if index % 3 == 0{

            if index % 5 == 0{

                output.append("FizzBuzz")

            }

            else{

                output.append("Fizz")

            }

        }

        else if index % 5 == 0{

            output.append("Buzz")

        }

        else{

            output.append(String(index))

        }

    }

    return output

}

5. 마무리

유명한 문제, 예전에도 아는 형한테 들었던 문제지만 간단하게 풀 수 있는 문제였다.

728x90

'알고리즘 > 해결' 카테고리의 다른 글

LeetCode821. Shortest Distance to a Character  (0) 2020.04.20
LeetCode226. Invert Binary Tree  (0) 2020.04.14
LeetCode868. Binary Gap  (0) 2020.04.12
LeetCode283. Move Zeroes  (0) 2020.04.12
LeetCode867. Transpose Matrix  (0) 2020.04.05