Python实现"Fizz Buzz"的一种方法

写一个程序,输出从1 - n对应的字符串表示

但是对3的倍数应该输出“Fizz”,对5的倍数应该输出“Buzz”,对即是3的倍数又是5的倍数应该输出“FizzBuzz”

Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]

1:for循环访问range(1, n+1),判断每一个数字满足的条件,添加对应字符串到outList列表尾

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

算法题来自:https://leetcode-cn.com/problems/fizz-buzz/description/

你可能感兴趣的:(Algorithms)