FizzBuzz in C++: Correct Solution, Explanation, and Complexity

FizzBuzz is a small interview exercise with one important lesson: turn the specification into mutually exclusive conditions in the right order. For each integer from 1 through n, print FizzBuzz when it is divisible by both 3 and 5, Fizz when it is divisible by 3, Buzz when it is divisible by 5, and otherwise print the integer.

Correct C++ solution

#include <iostream>

int main() {
    for (int value = 1; value <= 100; ++value) {
        if (value % 15 == 0) {
            std::cout << "FizzBuzz\n";
        } else if (value % 3 == 0) {
            std::cout << "Fizz\n";
        } else if (value % 5 == 0) {
            std::cout << "Buzz\n";
        } else {
            std::cout << value << '\n';
        }
    }
}

Why the combined case comes first

A multiple of 15 is also a multiple of both 3 and 5. If the program tests divisibility by 3 first, it prints Fizz for 15 and never reaches the combined case. Checking value % 15 == 0 first makes the branches disjoint and easy to verify.

Complexity and test cases

The loop runs once per input value, so time complexity is O(n). The algorithm uses O(1) extra space aside from output. Test 1, 3, 5, 15, and the final loop value; those cover the plain-number, each single divisor, combined divisor, and boundary cases.

What interviewers are checking

FizzBuzz is not about difficult algorithms. It tests whether you read the requirements, choose correct condition order, write a bounded loop, and explain a simple solution clearly. Do not over-engineer it with a map of divisors unless the question explicitly asks for a configurable version.

Reference: C++ arithmetic operators.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *