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

Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]
class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        #return ["FizzBuzz"*(i%15==0) or "Buzz"*(i%5==0) or "Fizz"*(i%3==0) or str(i) for i in range(1, n+1)]
        m = p = 0       
        ans = []
        for i in range(1, n+1):
            m += 1
            p += 1
            s = str(i)
            if m == 3 and p == 5:
                s = "FizzBuzz"
                m = p = 0
            elif m == 3:
                s = "Fizz"
                m = 0
            elif p == 5:
                s = "Buzz"
                p = 0
            ans.append(s)            
        return ans        
            

分别是用求余版本和不用求余版本。

记住 if else完全可以用and or 替代!


posted @ 2018-03-07 23:22  bonelee  阅读(233)  评论(0)    收藏  举报