美文网首页
【LeetCode】Fizz Buzz 解题报告

【LeetCode】Fizz Buzz 解题报告

作者: 负雪明烛 | 来源:发表于2017-01-02 18:01 被阅读0次

【LeetCode】Fizz Buzz 解题报告


[LeetCode]

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

  • 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”.

Ways

思路很简单,判断是否能特定位置的数字是否能被3和5整除即可。

方法一:

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

感觉好繁琐,python应该可以很简单。所以参考了别人的跟进如下。

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

嗯。这个看起来舒服多了。

Date

2017 年 1 月 2 日

相关文章

网友评论

      本文标题:【LeetCode】Fizz Buzz 解题报告

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