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的数字的字符串表示。

但对于三倍的倍数,它应输出“Fizz”而不是数字,并输出五个输出“Buzz”的倍数。 对于三个和五个输出“FizzBuzz”的倍数的数字。

Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]

思路: 如果是三的倍数,输出Fizz 5的倍数,输出Buzz 既是三的倍数也是5的倍数,输出FizzBuzz

返回类型:列表 分别做取余操作,看是否结果为0

from math import fmod

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

if __name__ == "__main__":
    n = 15
    print(Solution().fizzBuzz(n))

网上思路:

https://blog.csdn.net/NXHYD/article/details/72314080

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦