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

题目分析及思路

给定一正整数n,要求输出1-n的所有数字的的字符表示。其中三的倍数的数字输出“Fizz”,五的倍数的数字输出“Buzz”,若同时是三和五的倍数则输出“FizzBuzz”。可以遍历这个范围的所有数字,依次判断每个数字,对应输出它的字符表示。

python代码

class Solution:

    def fizzBuzz(self, n: int) -> List[str]:

        ans = []

        for i in range(1, n+1):

            if i % 3 == 0 and i % 5 == 0:

                ans.append('FizzBuzz')

            elif i % 3 == 0:

                ans.append('Fizz')

            elif i % 5 == 0:

                ans.append('Buzz')

            else:

                ans.append(str(i))

        return ans

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10464038.html