9 · Fizz Buzz 问题
描述
Given number n. Print number from 1 to n. According to following rules:
when number is divided by 3, print "fizz".
when number is divided by 5, print "buzz".
when number is divided by both 3 and 5, print "fizz buzz".
when number can't be divided by either 3 or 5, print the number itself.
样例
比如 n = 15, 返回一个字符串数组:
[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz", "11", "fizz",
"13", "14", "fizz buzz"
]
挑战
你是否可以只用一个 if 来实现
答:不可以
class Solution:
"""
@param n: An integer
@return: A list of strings.
"""
def fizzBuzz(self, n):
res = []
for i in range(1,n+1):
if i%15 == 0:
res.append("fizz buzz")
elif i%3 == 0:
res.append("fizz")
elif i%5 == 0:
res.append("buzz")
else:
res.append(str(i))
return res