# 412. Fizz Buzz Fizz Buzz

@TOC

[LeetCode]

https://leetcode.com/problems/fizz-buzz/open in new window

• Total Accepted: 31093
• Total Submissions: 53272
• Difficulty: Easy

##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"
]
``````

## # 解题方法

### # 方法一：遍历判断

``````class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
ListReturn = [];
x = 1
while x <= n:
if x % 3 == 0 and x % 5 == 0:
ListReturn.append("FizzBuzz")
elif x % 3 == 0:
ListReturn.append("Fizz")
elif x % 5 == 0:
ListReturn.append("Buzz")
else:
ListReturn.append(str(x))
x += 1
return ListReturn
``````

AC:69 ms

``````class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
return ["Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0)
+ str(i) * (i % 3 != 0 and i % 5 != 0)
for i in range(1, n + 1)]
``````

AC:96 ms

### # 方法二：字符串相加

``````class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
for i in range(1, n + 1):
pos = ""
if i % 3 == 0:
pos += "Fizz"
if i % 5 == 0:
pos += "Buzz"
if not pos:
pos = str(i)
res.append(pos)
return res
``````

### # 方法三：字典

``````class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
strmap = {3 : "Fizz", 5 : "Buzz"}
for i in range(1, n + 1):
pos = ""
for j in [3, 5]:
if i % j == 0:
pos += strmap[j]
if not pos:
pos = str(i)
res.append(pos)
return res
``````

## # 日期

2017 年 1 月 2 日 2018 年 11 月 8 日 —— 项目进展缓慢