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"
]
这个题倒是很简单,有很多种做法。
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
res=[]
while n>0:
if n%15==0:res.insert(0, "FizzBuzz")
elif n%3==0:res.insert(0, "Fizz")
elif n%5==0:res.insert(0, "Buzz")
else:res.insert(0, str(n))
n-=1
return res
看到discuss里有比较简洁的方法。
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
return [(not i%3)*"Fizz" + (not i%5)*"Buzz" or str(i) for i in range(1, n+1)]

本文探讨了经典的编程面试题FizzBuzz问题的多种解法,包括使用条件判断和利用列表推导式的简洁方法,展示了Python语言的强大和灵活。
314

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



