Problem
Given an integer n, return a string array answer (1-indexed) where:
- answer[i] == “FizzBuzz” if i is divisible by 3 and 5.
- answer[i] == “Fizz” if i is divisible by 3.
- answer[i] == “Buzz” if i is divisible by 5.
- answer[i] == i (as a string) if none of the above conditions are true.
Algorithm
Generate the string as required.
Code
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
for i in range(1, n + 1):
divide3 = (i % 3 == 0)
divide5 = (i % 5 == 0)
if divide3 and divide5:
ans.append("FizzBuzz")
elif divide3:
ans.append("Fizz")
elif divide5:
ans.append("Buzz")
else:
ans.append(str(i))
return ans