题目: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”.
即:输出字符串1到n,其中,3的倍数由 “Fizz” 代替,5的倍数由 “Buzz” 代替,15的倍数由 “FizzBuzz” 代替。
解题思路:使用if语句,判断数字是否是3,5或15的倍数即可。
代码:
class Solution(object):
def fizzBuzz(self, n):
list = [ ]
for i in range(n):
if (i+1) % 3 != 0 and (i+1) % 5 != 0:
list.append(str(i+1)) #要注意,i是从0开始的。
elif (i+1) % 3 == 0 and (i+1) % 5 != 0:
list.append("Fizz")
elif (i+1) % 5 == 0 and (i+1) % 3 != 0:
list.append("Buzz")
else:
list.append("FizzBuzz")
return list