1. 程式人生 > >【LintCode 簡單】9. Fizz Buzz 問題

【LintCode 簡單】9. Fizz Buzz 問題

1.問題描述:

給你一個整數n. 從 1 到 n 按照下面的規則列印每個數:

  • 如果這個數被3整除,列印fizz.
  • 如果這個數被5整除,列印buzz.
  • 如果這個數能同時被35整除,列印fizz buzz.
2.樣例:

比如 n = 15, 返回一個字串陣列:

[
  "1", "2", "fizz",
  "4", "buzz", "fizz",
  "7", "8", "fizz",
  "buzz", "11", "fizz",
  "13", "14", "fizz buzz"
]
3.程式碼:
class Solution:
    """
    @param: n: An integer
    @return: A list of strings.
    """
    def fizzBuzz(self, n):
        # write your code here
        answer=[]
        for i in range(1,n+1):
            if i%3==0 and i%5==0:
                answer.append("fizz buzz")
            elif i%3==0:
                answer.append("fizz")
            elif i%5==0:
                answer.append("buzz")
            else:
                answer.append(str(i))
        return answer