第八天 Fizz Buzz

作者: 业余马拉松选手 | 来源:发表于2018-08-27 23:32 被阅读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
        

相关文章

  • LeetCode 411-430

    412. Fizz Buzz[https://leetcode-cn.com/problems/fizz-buzz...

  • Leetcode PHP题解--D40 412. Fizz Bu

    412. Fizz Buzz 题目链接 412. Fizz Buzz 题目分析 这个题目也很简单。 从1逐个输出到...

  • Day 2: Prepare For FizzBuzz.z ->

    Fizz Buzz in Tensorflow interviewer: Welcome, can I get y...

  • 【LeetCode】Fizz Buzz 解题报告

    【LeetCode】Fizz Buzz 解题报告 [LeetCode] https://leetcode.com/...

  • 【LeetCode】Fizz Buzz 解题报告

    【LeetCode】Fizz Buzz 解题报告 [LeetCode] https://leetcode.com/...

  • Fizz Buzz

    写一个程序,输出从 1 到 n 数字的字符串表示。 如果 n 是3的倍数,输出“Fizz”; 如果 n 是5的倍数...

  • Fizz Buzz

    Write a program that outputs the string representation of...

  • Fizz Buzz

    问题描述 https://www.lintcode.com/problem/fizz-buzz/descripti...

  • Fizz Buzz

    写一个程序,输出从 1 到 n 数字的字符串表示。 如果 n 是3的倍数,输出“Fizz”; 如果 n 是5的倍数...

  • Fizz Buzz

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/fizz-b...

网友评论

    本文标题:第八天 Fizz Buzz

    本文链接:https://www.haomeiwen.com/subject/vhexwftx.html