第二周
選擇了一道看似很簡(jiǎn)單,同時(shí)也不難的題目:
https://leetcode-cn.com/problems/fizz-buzz/description/
這道題未舟,可以非常平鋪直敘的來(lái)做拯田,先看和%3和%5都等于0的震捣,然后再分別看%3和%5的岛蚤,嗯,結(jié)果我做這道題的時(shí)候到涂,還一直在想有沒(méi)有更好的方法脊框,結(jié)果用了這種字符串拼接的方法,實(shí)際反而更麻煩养盗。缚陷。。
好吧往核,先AC了吧
class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
retList = []
for i in range(1,n+1):
ret = ""
if i % 3 ==0:
ret += "Fizz"
if i % 5 ==0:
ret += "Buzz"
elif i % 5==0:
ret += "Buzz"
else:
ret += str(i)
retList.append(ret)
return retList
其實(shí)更好看點(diǎn)點(diǎn)的代碼應(yīng)該是:
class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
retList = []
for i in range(1,n+1):
if i % 3 == 0 and i % 5 == 0:
retList.append("FizzBuzz")
elif i % 3 == 0:
retList.append("Fizz")
elif i % 5 == 0:
retList.append("Buzz")
else:
retList.append(str(i))
return retList