Fizz Buzz: Ideal solution

Viewed 645

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?

1 Answers

I don't think you need an entire string just to check if anything is printed, a single bool would do. Besides that, I'd collect the numbers in an array for easy extensibility. Other than that, your second solution seems pretty okay. Here's my go at it:

#include <cstdio>
#include <utility>

void fizzbuzz(int const range) noexcept {
    constexpr std::pair<int, char const*> pairs[] {
        {3, "Fizz"}, {5, "Buzz"}, {7, "Fuzz"}, {13, "Bizz"}
    };

    for (int i = 1; i < range; ++i) {
        bool none = true;
        for (auto const& [num, str] : pairs) {
            if (i % num == 0) {
                std::printf("%s", str);
                none = false;
            } 
        }

        if (none) {
            std::printf("%d", i);
        }
        std::putchar('\n');
    }
}
Related