복's

[ LeetCode - 412 ] Fizz Buzz 본문

알고리즘/LeetCode

[ LeetCode - 412 ] Fizz Buzz

나복이 2023. 10. 29. 22:33
728x90

https://leetcode.com/problems/fizz-buzz/

 

Fizz Buzz - LeetCode

Can you solve this real interview question? Fizz Buzz - 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

leetcode.com

크게 어려운것 없었다.

3 6 9 게임처럼 1 2 3 4 5 6 7 8 9 ~ 있으면 3, 6, 9만 다른 글자로 변경해준다고 생각하면 편할 것 같다.


[ 📌 풀이 ]

1) 주어진 수 n 만큼 순회 한다.

2 - 1) 3과 5의 배수라면 "FizzBuzz"를 삽입힌다.

2 - 2) 3의 배수라면 "Fizz"를 삽입한다.

2 - 3) 5의 배수라면 "Buzz"를 삽입한다.

2 - 4) 어디에도 속하지 않는다면 순회중인 인덱스를 문자열로 삽입한다.


[ 📌 코드 - Python ]

class Solution:
    def fizzBuzz(self, n: int) -> list[str]:
        answer = []
        
        for idx in range(1, n + 1):
            div_five = idx % 5
            div_three = idx % 3

            if div_three == 0 and div_five == 0:
                answer.append("FizzBuzz")
            elif div_three == 0:
                answer.append("Fizz")
            elif div_five == 0:
                answer.append("Buzz")
            else:
                answer.append(str(idx))

        return answer

[ 📌 결과 ]

[ Result ]

728x90