PU Fizz Buzz

Jan 01, 1970

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

Python Solution 1:

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        res = [""] * n
        _p3 = 3
        while _p3 <= n:
            res[_p3 - 1] += "Fizz"
            _p3 += 3
        _p5 = 5
        while _p5 <= n:
            res[_p5 - 1] += "Buzz"
            _p5 += 5
        for i in range(n):
            if not res[i]:
                res[i] = str(i + 1)
        return res

Python Solution 2:

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

Python Solution 3:

def fizzBuzz(self, n):
    return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]

Summary:

  • Solution 1 is bad because of string plus.
  • Solution 3 maybe better than solution 2.

LeetCode: 412. Fizz Buzz