Fizz Buzz Problem
Description
LeetCode Problem 412.
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 if non of the above conditions are true.
Example 1:
1
2
Input: n = 3
Output: ["1","2","Fizz"]
Example 2:
1
2
Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]
Example 3:
1
2
Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Constraints:
- 1 <= n <= 10^4
Sample C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> res(n);
for(int i = 1; i <= n; i++) {
res[i - 1] = to_string(i);
}
for(int i = 2; i < n; i += 3) {
res[i] = "Fizz";
}
for(int i = 4; i < n; i += 5) {
res[i] = "Buzz";
}
for(int i = 14; i < n; i += 15) {
res[i] = "FizzBuzz";
}
return res;
}
};