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 a string array
answer
of sizen
to store the results. - Iteration: Iterate from 1 to
n
(inclusive). - Divisibility Check: For each number
i
, check the following conditions in order:- If
i
is divisible by both 3 and 5, add "FizzBuzz" toanswer
. - Otherwise, if
i
is divisible by 3, add "Fizz" toanswer
. - Otherwise, if
i
is divisible by 5, add "Buzz" toanswer
. - Otherwise, add the string representation of
i
toanswer
.
- If
- Return: Return the
answer
array.
Explanation
The solution directly implements the problem's requirements. The order of the if
conditions is crucial. We check for divisibility by both 3 and 5 first to ensure that "FizzBuzz" is correctly assigned when a number is divisible by both. If we checked for divisibility by 3 and 5 separately before checking for both, numbers divisible by both would incorrectly be labeled only "Fizz" or "Buzz".
Code
using System;
public class Solution {
public IList<string> FizzBuzz(int n) {
IList<string> answer = new List<string>();
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
answer.Add("FizzBuzz");
} else if (i % 3 == 0) {
answer.Add("Fizz");
} else if (i % 5 == 0) {
answer.Add("Buzz");
} else {
answer.Add(i.ToString());
}
}
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 stores n strings.