Fizz Buzz problem states that given an integer n, for every integer i <= n, the task is to write a C++ program to print,
- 'FizzBuzz' if i is divisible by 3 and 5,
- 'Fizz' if i is divisible by 3,
- 'Buzz' if i is divisible by 5
- 'i' as a string, if none of the conditions are true.
Example:
Input: n = 3
Output: [1 2 Fizz]
Input: n = 10
Output: [1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz]
Input: n = 20
Output: [1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz]
Naive Approach - By checking every condition individually
A very simple approach to solve this problem is that we can start checking each number from 1 to n to see if it's divisible by 3, 5, or both. Depending on the divisibility:
- If a number is divisible by both 3 and 5, append "FizzBuzz" into result.
- If it's only divisible by 3, append "Fizz" into result.
- If it's only divisible by 5, append "Buzz" into result..
- Otherwise, append the number itself into result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector<string> fizzBuzz(int n){
vector<string> result;
for (int i = 1; i <= n; ++i) {
// Check if i is divisible by both 3 and 5
if (i % 3 == 0 && i % 5 == 0) {
// Add "FizzBuzz" to the result vector
result.push_back("FizzBuzz");
}
// Check if i is divisible by 3
else if (i % 3 == 0) {
// Add "Fizz" to the result vector
result.push_back("Fizz");
}
// Check if i is divisible by 5
else if (i % 5 == 0) {
// Add "Buzz" to the result vector
result.push_back("Buzz");
}
else {
// Add the current number as a string to the
// result vector
result.push_back(to_string(i));
}
}
return result;
}
int main(){
int n = 10;
vector<string> result = fizzBuzz(n);
for (const string& s : result) {
cout << s << " ";
}
return 0;
}
Output1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz
Time Complexity: O(n), since we need to traverse the numbers from 1 to n in any condition.
Auxiliary Space: O(n), for storing the result
By String Concatenation
While the naive approach works well for the basic FizzBuzz problem, it becomes very complicated if additional mappings comes under picture, such as "Jazz" for multiples of 7. The number of conditions for checking would increases.
Instead of checking every possible combination of divisors, we check each divisor separately and concatenate the corresponding strings if the number is divisible by them.
Let's see the step-by-step approach:
- For each number i <= n, start with an empty word res.
- Check if i is divisible by 3, append "Fizz" into res.
- Check if i is divisible by 5, append "Buzz" into res.
- If we add "Fizz" and "Buzz", the res becomes "FizzBuzz" and we don't need extra comparisons to check divisibility of both.
- If nothing was added, just use the number.
- Finally, append this res into our result array.
C++
#include <bits/stdc++.h>
using namespace std;
vector<string> fizzBuzz(int n){
vector<string> result;
for (int i = 1; i <= n; i++){
// Initialize an empty string for the current result
string res = "";
// Divides by 3, add Fizz
if (i % 3 == 0)
res += "Fizz";
// Divides by 5, add Buzz
if (i % 5 == 0)
res += "Buzz";
// Not divisible by 3 or 5, add the number
if (res.empty())
res += to_string(i);
// Append the current res to the result vector
result.push_back(res);
}
return result;
}
int main(){
int n = 10;
vector<string> result = fizzBuzz(n);
for (const string &str : result)
cout << str << " ";
return 0;
}
Output1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz
Time Complexity: O(n), since we need to traverse the numbers from 1 to n in any condition.
Auxiliary Space: O(n), for storing the result
Using Hashing
When we have many words to add like "Fizz", "Buzz", "Jazz" and more, the second method can still get complicated. To make things cleaner, we can use something called a hash table (in C++, it's called unordered_map). Initially, we can store the divisors and their corresponding words into hash table.
For this problem, first we'll map 3 to "Fizz" and 5 to "Buzz" into unordered_map and for each number i <= n, do the following:
- Start with an empty word res
- Checks if it i divisible by 3 or 5,
- Appends the corresponding string from map to the res.
- If the number is not divisible by either, simply adds the number itself as a string into res.
- Finally, append res into result.
C++
#include <bits/stdc++.h>
using namespace std;
vector<string> fizzBuzz(int n){
vector<string> result;
// Hash map to store all fizzbuzz mappings.
unordered_map<int, string> mp = {{3, "Fizz"}, {5, "Buzz"}};
// List of divisors which we will iterate over.
vector<int> divisors = {3, 5};
for (int i = 1; i <= n; i++){
string res = "";
for (int d : divisors){
// If the i is divisible by d,
// then add the corresponding string mapping to current res
if (i % d == 0)
res += mp[d];
}
// Not divisible by 3 or 5, add the number
if (res.empty())
res += to_string(i);
// Append the current answer str to the result vector
result.push_back(res);
}
return result;
}
int main(){
int n = 10;
vector<string> result = fizzBuzz(n);
for (const string &s : result)
cout << s << " ";
return 0;
}
Output1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz
Time Complexity: O(n), since we need to traverse the numbers from 1 to n in any condition.
Auxiliary Space: O(n), for storing the result and for hash table
Similar Reads
Fizz Buzz Given an integer n, for every positive integer i <= n, the task is to print,"FizzBuzz" if i is divisible by 3 and 5, "Fizz" if i is divisible by 3,"Buzz" if i is divisible by 5"i" as a string, if none of the conditions are true.Examples:Input: n = 3Output: ["1", "2", "Fizz"]Input: n = 10Output: [
15+ min read
Fizz Buzz in Python Fizz Buzz Problem involves that given an integer n, for every integer i <= n, the task is to write a Python program to print,'FizzBuzz' if i is divisible by 3 and 5, 'Fizz' if i is divisible by 3, 'Buzz' if i is divisible by 5'i' as a string, if none of the conditions are true.Example:Input: n =
5 min read
Fizz Buzz Implementation | Set 2 Given an integer N, the task is to print all the numbers from 1 to N replacing the multiples of 3, 5 and both 3 and 5 by âFizzâ, âBuzzâ and "Fizz Buzz" respectively. Examples: Input: N = 5Output: 1, 2, Fizz, 4, Buzz Input: N = 15Output: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14Fi
7 min read
fabs() in C++ The fabs() function returns the absolute value of the argument. Mathematically |a|. If a is value given in the argument. Syntax: double fabs(double a); float fabs(float a); int fabs(int a); Parameter: The fabs() function takes a single argument, a whose absolute value has to be returned. Return: The
2 min read
frexp() in C++ The frexp() function breaks the floating point number x into its binary significand i., e., floating point with an absolute value between [0.5, 1.0) and an integral exponent for 2. x = significand * (2^exponent). It used to : 1. It is used to find significand which is always between 0.5 and 1.0 2. I
2 min read
iota() in C++ In C++, iota() is a library function used to fill a range of elements with increasing values starting from the given initial value. It assigns the starting value to the first element and then increments it once for the next element and so on.Let's take a look at an example:C++#include <bits/stdc+
3 min read
raise() function in C++ csignal header file declared the function raise() to handle a particular signal. Signal learns some unusual behavior in a program, and calls the signal handler. It is implemented to check if the default handler will get called or it will be ignored. Syntax: int raise ( int signal_ ) Parameter: The f
3 min read
Avoid Bugs Using Modern C++ C++ has more constructs that can cause undefined behavior or exceptions as compared to languages like Java and Python. This is because C++ was developed with a primary objective to include classes in C and hence, support bug-inviting features such as pointers, macros, etc. It is also devoid of tools
3 min read
Function Pointer in C++ Prerequisites: Pointers in C++Function in C++ Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of point
4 min read
C++ Modify Pointers Prerequisite: Pointer in C++ Pointers are an essential part of the C++ language. It allows us to store the memory address of a variable. One thing to note here is that if we change the value that a pointer is pointing to, then the value of the original variable also changes. Now, let's check the app
2 min read