您的位置:首页 > 编程语言 > Python开发

【LeetCode-Python】412. Fizz Buzz

2016-10-19 09:36 405 查看
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)]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode