The problem “Fizz Buzz” asks you to write a program that outputs a string representation of numbers from 1 to n
. For multiples of three, it should output “Fizz” instead of the number and for the multiples of five, output “Buzz”. For numbers which are multiples of both three and five, output “FizzBuzz”.
n
we should consider?
n
to be a positive integer in a reasonable range (e.g., 1 to 10,000).1
to n
.#include <iostream>
#include <vector>
#include <string>
std::vector<std::string> fizzBuzz(int n) {
std::vector<std::string> result;
for (int i = 1; i <= n; ++i) {
if (i % 15 == 0) {
result.push_back("FizzBuzz");
} else if (i % 3 == 0) {
result.push_back("Fizz");
} else if (i % 5 == 0) {
result.push_back("Buzz");
} else {
result.push_back(std::to_string(i));
}
}
return result;
}
// Sample usage
int main() {
int n = 15; // example input
std::vector<std::string> result = fizzBuzz(n);
for (const std::string& s : result) {
std::cout << s << std::endl;
}
return 0;
}
n
exactly once.n
.This solution is efficient and straightforward, working within the constraints typically set for such problems.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?