1. 程式人生 > >【python】【leetcode】【演算法題目412—Fizz Buzz】

【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

四、其他