【python】【leetcode】【算法题目412—Fizz Buzz】

一、题目描述

题目原文:

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

(依次输出1~n按以下要求的代替:若数字为3的倍数则输出“Fizz”;若数字是5的倍数,则输出“Buzz”;

若数字既是3的倍数又是5的倍数则输出“FizzBuzz”;其余数字输出数字本身。)

二、题目分析

思路:很简单依次循环判断即可。

三、Python代码

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        result = []
        for i in range(1, n+1):
            if i % 3 == 0 and i % 5 == 0:
                result.append("FizzBuzz")
            elif i % 3 == 0:
                result.append("Fizz")
            elif i % 5 == 0:
                result.append("Buzz")
            else:
                result.append(str(i))
        return result

四、其他

题目链接:https://leetcode.com/problems/fizz-buzz/

Runtime: 72 ms

想法不够优化,欢迎大家留言交流~

你可能感兴趣的:(leetcode,-,python实现,python,leetcode,算法题目412,Fizz,Buzz)