[leetcode] 412. Fizz Buzz @ python

原题

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

解法

一次遍历, 直接在列表中重新赋值, 注意需要赋值给res[i]而不是num in res, 因此我们用for i in range(len(res))来遍历.
Time: O(n)
Space: O(1)

代码

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        res = list(range(1, n+1))
        
        for i in range(len(res)):
            if res[i] % 15 == 0:
                res[i] = 'FizzBuzz'
            elif res[i] % 3 == 0:
                res[i] = 'Fizz'
            elif res[i] % 5 == 0:
                res[i] = 'Buzz'
            else:
                res[i] = str(res[i])
                
        return res

你可能感兴趣的:([leetcode] 412. Fizz Buzz @ python)