412. Fizz Buzz

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

解法

常规解法

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

        return res

时间复杂度:O(n)O(n)

空间复杂度:???。

一行解法

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

不使用模运算

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

        for i in range(1, n + 1):
            fizz += 1
            buzz += 1

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

        return ret

Last updated

Was this helpful?