【LeetCode-Python】412. Fizz Buzz

来源:互联网 发布:淘宝网鞋子女鞋春季 编辑:程序博客网 时间:2024/06/05 22:52

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”
]
简单解释:3的倍数位置替换为Fizz,5的倍数位置替换为Buzz,15的倍数位置替换为FizzBuzz
Solution1[Python]:

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

Solution2[Python]: just one line

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