So, Fizz Buzz is a very simple problem and there are quite a lot of solutions to this problem. In a recent interview, the interviewer asked me to write a function for Fizz Buzz, So I single-handedly came up with the following approach.
void fizz_buzz(int range) {
for(auto i = 1; i < range; ++i) {
if(i % 15 == 0)
cout << "FizzBuzz" << "\n";
else if(i % 3 == 0)
cout << "Fizz" << "\n";
else if(i % 5 == 0)
cout << "Buzz" << "\n";
else
cout << i << "\n";
}
}
And then the interviewer asked me what If I wanted to modify Fizz Buzz for 3 and 7 then in your code multiple conditional statements would have to be changed.
So, I wrote the following snippet:
void fizz_buzz(int range) {
//Notice that we don't need to check for divisibility by both values now
int i = 0;
for(i = 1; i < range; ++i) {
string str;
if(i % 3 == 0)
str += "Fizz";
if(i % 5 == 0)
str += "Buzz";
if(str.empty())
str += to_string(i);
cout << str << " ";
}
}
But, again the interviewer said that he is not satisfied with this approach also. What should be an ideal way to approach Fizz Buzz then?