알고리즘

[LeetCode] Fizz Buzz

유병각 2022. 4. 23. 20:28

[LeetCode] Fizz Buzz

풀이_#1

반복문과 조건문 활용

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        r = [];

        for i in range(1, n+1):
            s = str(i);
            if (i % 3 == 0 and i % 5 == 0):
                s = "FizzBuzz"
            elif (i % 3 == 0):
                s = "Fizz"
            elif (i % 5 == 0):
                s = "Buzz"
            r.append(s)
        return r

풀이_#2

리스트 이해 응용

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        return ["Fizz" * (not i % 3) + "Buzz" * (not i % 5) or str(i) for i in range(1,n+1)]