Write a program that outputs the string representation of numbers from 1 to N.
But 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”.
Input format
First line contains an integer representing the value of N.
Output format
Return an array of strings where each string is either Fizz (for multiples of 3 and NOT 5) or Buzz (for multiples of 5 and NOT 3) or FizzBuzz (for multiples of BOTH 3 and 5) or an integer (For multiples of NEITHER 3 NOR 5).
Sample Input 1
15
Sample Output 1
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Explanation 1
For n = 1 , 1 is printed.
For n = 3 , Fizz is printed.
For n = 5 , Buzz is printed.
For n = 15 , FizzBuzz is printed.
Constraints
1 <= N <= 100000
Solution
Let's write the program in C++ to solve the FizzBuzz problem based on the given description and constraints.
### Steps to Implement the Solution
1. Read the integer \( N \) from input.
2. Create a loop from 1 to \( N \).
3. For each number in the loop:
- Print "FizzBuzz" if the number is divisible by both 3 and 5.
- Print "Fizz" if the number is divisible by 3 but not by 5.
- Print "Buzz" if the number is divisible by 5 but not by 3.
- Print the number itself if it is not divisible by either 3 or 5.
### C++ Code
Here's the implementation of the solution:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> fizzBuzz(int N) {
vector<string> result;
for (int i = 1; i <= N; ++i) {
if (i % 3 == 0 && i % 5 == 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(to_string(i));
}
}
return result;
}
int main() {
int N;
cin >> N;
vector<string> output = fizzBuzz(N);
for (const string &s : output) {
cout << s << endl;
}
return 0;
}
### Explanation
1. **Input Handling**: The integer \( N \) is read from standard input.
2. **Loop and Conditions**:
- For numbers divisible by both 3 and 5, "FizzBuzz" is added to the result.
- For numbers divisible by only 3, "Fizz" is added.
- For numbers divisible by only 5, "Buzz" is added.
- For other numbers, the number itself (as a string) is added.
3. **Output**: The results are printed line by line.
### Sample Run
Given the sample input:
15
The output would be:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
This code handles up to 100,000 efficiently by only performing simple modulus operations and string operations. Each number is processed in constant time, ensuring the program runs efficiently even for the upper limit of \( N \).
No comments:
Post a Comment