動機
超常見水題
Problem
Given an integer n
, return a string array answer
(1-indexed) where:
answer[i] == FizzBuzz
ifi
is divisible by3
and5
.answer[i] == Fizz
ifi
is divisible by3
.answer[i] == Buzz
ifi
is divisible by5
.answer[i] == i
if non of the above conditions are true.
Example 1:
Input: n = 3Output: [1,2,Fizz]
Example 2:
Input: n = 5Output: [1,2,Fizz,4,Buzz]
Example 3:
Input: n = 15Output: [1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz]
Constraints:
1 <= n <= 104
Sol
class Solution:
def fizzBuzz(self, n):
def f(i):
if i % 5 == 0 and i % 3 == 0:
return "FizzBuzz"
elif i % 5 == 0:
return "Buzz"
elif i % 3 == 0:
return "Fizz"
else:
return str(i)
return [f(i) for i in range(1,n+1)]