Fizz Buzz
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
(as a string) if none of the above conditions are true.
Constraints
1 <= n <= 104
Solution
The problem Fizz Buzz
can be solved by simply setting the string based on the description given.
Implementation
class Solution
{
public:
vector<string> fizzBuzz(int n)
{
vector<string> ret;
ret.reserve(n);
for (int i = 1; i <= n; i++)
{
if (i % 3 == 0 && i % 5 == 0)
ret.push_back("FizzBuzz");
else if (i % 3 == 0)
ret.push_back("Fizz");
else if (i % 5 == 0)
ret.push_back("Buzz");
else
ret.push_back(to_string(i));
}
return ret;
}
};