LeetCode 412. Fizz Buzz

題目:

如例題: 3的倍數用Fizz代替,5用Buzz,同時是3跟5的倍數用FizzBuzz代替。

n = 15,

Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]

思路:

  1. result = []
  2. for i in range(1, n+1):
    if i % 15 ==0:
    result.append(“FizzBuzz”)
    elif i %3 ==0:
    result.append(“Fizz”)
    elif i %5 ==0:
    result.append(“Buzz”)
    else:
    result.append(str(i))
  3. return result

Coding:

class Solution:
def fizzBuzz(self, n: int) -> List[str]:
result = []
for i in range(1, n+1):
if i % 15 ==0:
result.append("FizzBuzz")
elif i %3 ==0:
result.append("Fizz")
elif i %5 ==0:
result.append("Buzz")
else:
result.append(str(i))
return result

--

--

Sharko Shen
Data Science & LeetCode for Kindergarten

Thinking “Data Science for Beginners” too hard for you? Check out “Data Science for Kindergarten” !