LeetCode 412. Fizz Buzz

撰写于 2018-01-03 修改于 2018-01-21 分类 LeetCode 标签 LeetCode

Question

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

Solution

The solution is simple

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
outputs = []
for i in range(1, n+1):
if i % 3 == 0 and i % 5 != 0:
outputs.append('Fizz')
elif i % 3 !=0 and i % 5 == 0:
outputs.append('Buzz')
elif i % 3 == 0 and i % 5 == 0:
outputs.append('FizzBuzz')
else:
outputs.append(str(i))
return outputs

Or more clean one

1
2
3
4
5
6
7
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]
Site by GoingMyWay using Hexo & Random
备案号: 粤ICP备16087705号-1

I am a ML and RL research student

Hide