Fizz Buzz

Given an integer , return a string array answer (1-indexed) where:

  • answer[i] == "FizzBuzz" if is divisible by both 3 and 5
  • answer[i] == "Fizz" if is divisible by 3
  • answer[i] == "Buzz" if is divisible by 5
  • answer[i] == to_string(i) otherwise

This classic interview problem tests basic loop construction and conditional logic. The key insight is checking divisibility using the modulo operator.

Basic Solution

 
#include <string>
#include <vector>
using namespace std;
 
class Solution {
public:
  vector<string> fizzBuzz(int n) {
    vector<string> out = {};
    for (int i = 0; i < n; ++i) {
      out.push_back("");
      if ((i+1) % 3 == 0) {
        out[i] += "Fizz";
      }
      if ((i+1) % 5 == 0) {
        out[i] += "Buzz";
        continue;
      }
      if (out[i] == "") {
        out[i] = to_string(i+1);
      }
    }
    return out;
  }
};

Clean Solution

A more straightforward approach uses push_back() directly in each conditional branch, avoiding string concatenation and empty string checks:

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string>v;
        for(int i=1;i<=n;i++){
            if ((i%3==0) && (i%5==0)){
                v.push_back("FizzBuzz");
            }else if(i%3==0){
                v.push_back("Fizz");
            }else if(i%5==0){
                v.push_back("Buzz");
            }else{
                v.push_back(to_string(i));
            }
        }
        return v;
    }
};