给你一个整数 n
,找出从 1
到 n
各个整数的 Fizz Buzz 表示,并用字符串数组 answer
(下标从 1 开始)返回结果,其中:
answer[i] == "FizzBuzz"
如果 i
同时是 3
和 5
的倍数。answer[i] == "Fizz"
如果 i
是 3
的倍数。answer[i] == "Buzz"
如果 i
是 5
的倍数。answer[i] == i
(以字符串形式)如果上述条件全不满足。示例 1:
输入:n = 3 输出:["1","2","Fizz"]
示例 2:
输入:n = 5 输出:["1","2","Fizz","4","Buzz"]
示例 3:
输入:n = 15 输出:["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
提示:
1 <= n <= 104
实现的是经典的FizzBuzz问题,即对从1到n的每个整数进行如下操作:如果该数能被3整除,就在答案中添加"Fizz";如果该数能被5整除,就在答案中添加"Buzz";如果该数能同时被3和5整除,就在答案中添加"FizzBuzz"。如果都不能,就将该数本身添加到答案中。
answer
的空列表,用于存储结果。for
循环遍历从1到n的每个整数(在Python中,range(n)
生成一个从0到n-1的整数序列)。)。如果能,就在
answer`中添加字符串"FizzBuzz",然后跳过本次循环,准备处理下一个整数。)。如果能,就在
answer`中添加字符串"Fizz",然后跳过本次循环。)。如果能,就在
answer`中添加字符串"Buzz",然后跳过本次循环。answer
中。answer
列表。class Solution:
def fizzBuzz(self, n: int) -> list[str]:
answer=[]
for i in range(n):
if (i+1)%15==0:
answer.append("FizzBuzz")
elif (i+1)%3==0:
answer.append("Fizz" )
elif (i+1)%5==0:
answer.append("Buzz")
else:
answer.append(str(i+1))
return answer