原题
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”
]
解法
一次遍历, 直接在列表中重新赋值, 注意需要赋值给res[i]而不是num in res, 因此我们用for i in range(len(res))来遍历.
Time: O(n)
Space: O(1)
代码
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = list(range(1, n+1))
for i in range(len(res)):
if res[i] % 15 == 0:
res[i] = 'FizzBuzz'
elif res[i] % 3 == 0:
res[i] = 'Fizz'
elif res[i] % 5 == 0:
res[i] = 'Buzz'
else:
res[i] = str(res[i])
return res
本文介绍了一个经典的编程问题-FizzBuzz的解决方案。对于1到n的每个数字,如果数字能被3整除则输出'Fizz',能被5整除则输出'Buzz',同时被3和5整除则输出'FizzBuzz',其余情况输出数字本身。通过一次遍历和直接在列表中重新赋值的方式,实现了高效的时间和空间复杂度。
465

被折叠的 条评论
为什么被折叠?



