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)]