Leetcode刷题笔记

第八天 Fizz Buzz

2018-08-27  本文已影响7人  业余马拉松选手

第二周

选择了一道看似很简单,同时也不难的题目:

https://leetcode-cn.com/problems/fizz-buzz/description/

这道题,可以非常平铺直叙的来做,先看和%3和%5都等于0的,然后再分别看%3和%5的,嗯,结果我做这道题的时候,还一直在想有没有更好的方法,结果用了这种字符串拼接的方法,实际反而更麻烦。。。

好吧,先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

其实更好看点点的代码应该是:

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
        
上一篇 下一篇

猜你喜欢

热点阅读