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 vector
answer
of sizen
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 using the modulo operator (%
). If true, add "FizzBuzz" toanswer
. - Otherwise, check if
i
is divisible by 3. If true, add "Fizz" toanswer
. - Otherwise, check if
i
is divisible by 5. If true, add "Buzz" toanswer
. - Otherwise, convert
i
to a string usingto_string()
and add it toanswer
.
- Check if
- Return: Return the
answer
vector.
Explanation:
The solution uses a simple iterative approach with conditional statements to check the divisibility of each number by 3 and 5. The modulo operator (%) efficiently determines if a number is divisible by another. The to_string()
function converts integers to strings for cases where the number is not divisible by 3 or 5.
Code:
#include <string>
#include <vector>
class Solution {
public:
std::vector<std::string> fizzBuzz(int n) {
std::vector<std::string> answer(n);
for (int i = 1; i <= n; ++i) {
if (i % 3 == 0 && i % 5 == 0) {
answer[i - 1] = "FizzBuzz";
} else if (i % 3 == 0) {
answer[i - 1] = "Fizz";
} else if (i % 5 == 0) {
answer[i - 1] = "Buzz";
} else {
answer[i - 1] = std::to_string(i);
}
}
return answer;
}
};
Complexity:
- Time Complexity: O(n), where n is the input integer. We iterate through the numbers from 1 to n once.
- Space Complexity: O(n), as we store the results in a string vector of size n.