【LeetCode】Fizz Buzz 解题报告

来源:互联网 发布:软件项目管理案例 编辑:程序博客网 时间:2024/05/24 07:44

【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 日

0 0
原创粉丝点击