Description

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 <= 104

Submitted Code

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        result = []
        for i in range(1, n+1):
            if i % 3 == 0 and i % 5 == 0:   # i % 15 == 0
                result.append("FizzBuzz")
            elif i % 3 == 0:
                result.append("Fizz")
            elif i % 5 == 0:
                result.append("Buzz")
            else:
                result.append(str(i))
        
        return result

Runtime: 0 ms | Beats 100.00%
Memory: 13.30 MB | Beats 85.63%

유명한 프로그래밍 문제로, 전통적인 방식으로 해결했다.

Other Solutions

1st

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

time complexity: 𝑂(𝑛)
space complexity: 𝑂(𝑛)

파이썬에서 True는 1, False는 0처럼 사용되는 것을 이용하여 3 또는 5의 배수가 아니면 빈 문자열로 만드는 방법이다. 또 빈 문자열 또한 False 취급되기 때문에 3이나 5의 배수가 아니면 or 연산자 뒤의 str(i)가 반환된다.

n = 15

("Fizz" * 0  +  "Buzz" * 0) or str(1)  =  1
("Fizz" * 0  +  "Buzz" * 0) or str(2)  =  2
("Fizz" * 1  +  "Buzz" * 0) or str(3)  =  "Fizz"
("Fizz" * 0  +  "Buzz" * 0) or str(4)  =  4
("Fizz" * 0  +  "Buzz" * 1) or str(5)  =  "Buzz"
...
("Fizz" * 1  +  "Buzz" * 1) or str(15) =  "FizzBuzz"

return [“1”,”2”,”Fizz”,”4”,”Buzz”,”Fizz”,”7”,”8”,”Fizz”,”Buzz”,”11”,”Fizz”,”13”,”14”,”FizzBuzz”]

2nd

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        res = []
        i, fizz, buzz = 1, 0, 0

        while i <= n:
            fizz += 1
            buzz += 1

            if fizz == 3 and buzz == 5:
                res.append("FizzBuzz")
                fizz = buzz = 0
            elif fizz == 3:
                res.append("Fizz")
                fizz = 0
            elif buzz == 5:
                res.append("Buzz")
                buzz = 0
            else:
                res.append(str(i))

            i += 1

        return res

% 연산자 없이 푸는 방법도 참고했다.

Leave a comment