【LeetCode】412. Fizz Buzz

本文提供了一种使用Python解决经典编程挑战FizzBuzz的方法。通过两种不同的实现方式,展示了如何优雅地处理数字1到n的字符串表示,并针对3和5的倍数进行特殊处理。

Python版本:python3.6.2

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

Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]
交作业啦
class Solution:
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        res = []
        for i in range(1, n+1):
            if not i % 3 and not i % 5:
                res.append("FizzBuzz")
            elif not i % 3:
                res.append("Fizz")
            elif not i % 5:
                res.append("Buzz")
            else:
                res.append(str(i))
        return res
检验一下:
a = Solution()
print(a.fizzBuzz(15))
运行结果:

"D:\Program files\python3.6.2\python.exe" "D:/sunfl/sunflower/study/LeetCode/412. Fizz Buzz/412. Fizz Buzz.py"
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']

进程已结束,退出代码0
速度:

这是迄今为止我最好的成绩了,超过50%啦哈哈哈,感觉有点没出息,没事慢慢来,每天进步一点点o(* ̄▽ ̄*)ブ

再来看看大神代码:
class Solution:
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        def fizzBuzz(self, n):
            return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n + 1)]
这里胜在想法,通过字符串拼接的方式省去了if else的判断,简洁漂亮!
要注意:
or
print("1" or "2")  #返回1
print("fffff" or "2") #返回fffff
这里,or 作或判断,“1”、“2”、"fffff"都被视为真,故返回最左边的那个。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值