Fizz Buzz easy
Problem Statement
Given an integer n
, return a string array answer
(1-indexed) where:
answer[i] == "FizzBuzz"
ifi
is divisible by 3 and 5.answer[i] == "Fizz"
ifi
is divisible by 3.answer[i] == "Buzz"
ifi
is divisible by 5.answer[i] == i
(as a string) if none of the above conditions are true.
Example 1
Input: n = 3 Output: ["1","2","Fizz"]
Example 2
Input: n = 5 Output: ["1","2","Fizz","4","Buzz"]
Steps
- Initialization: Create an empty list
answer
to store the results. - Iteration: Iterate through numbers from 1 to
n
(inclusive). - Divisibility Check: For each number
i
:- Check if
i
is divisible by both 3 and 5. If true, append "FizzBuzz" toanswer
. - Otherwise, check if
i
is divisible by 3. If true, append "Fizz" toanswer
. - Otherwise, check if
i
is divisible by 5. If true, append "Buzz" toanswer
. - Otherwise, append the string representation of
i
toanswer
.
- Check if
- Return: Return the
answer
list.
Explanation
The solution uses a simple iterative approach. The order of the checks is crucial. We first check for divisibility by both 3 and 5 to ensure that "FizzBuzz" takes precedence over "Fizz" or "Buzz" when a number is divisible by both. The %
operator (modulo operator) is used to check for divisibility. If a % b == 0
, then a
is divisible by b
. The str(i)
converts the integer i
to its string representation.
Code
def fizzBuzz(n):
"""
Generates a FizzBuzz sequence up to n.
Args:
n: An integer representing the upper limit of the sequence.
Returns:
A list of strings representing the FizzBuzz sequence.
"""
answer = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
answer.append("FizzBuzz")
elif i % 3 == 0:
answer.append("Fizz")
elif i % 5 == 0:
answer.append("Buzz")
else:
answer.append(str(i))
return answer
Complexity
- Time Complexity: O(n) - The code iterates through the numbers from 1 to n once.
- Space Complexity: O(n) - The
answer
list can store up to n strings.