Nimitz
Nimitz

Reputation: 3

C++ Fizzbuzz Leetcode vector push_back() replacing all previous elements

I am having an issue where the C++ push_back() function is replacing all previous elements in a vector. Code that works is given

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

will output

["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

meanwhile my code

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

will output

["FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz","FizzBuzz"]

If the testcase is 3 it will be ["Fizz", "Fizz", "Fizz"] or if the testcase if 4 it will be ["1", "2", "3", "4"]

Essentially the last value replaces all previous elements with that specific answer.

Given that my code and the answer code is almost exactly the same (except my vector is named ok and the answer vector is named ans, why is my code causing an issue with push_back()?

Upvotes: 0

Views: 506

Answers (1)

Nan M
Nan M

Reputation: 1

Your logic is correct, but when you are using if and else if you are giving conditions on 'n' instead of 'i'.Try changing them, you will get the correct answer.

vector<string> fizzBuzz(int n) {
      vector<string> os;
        for (int i = 1; i <= n; i++) {
            if (i %15==0 ) {
                os.push_back("FizzBuzz");}
            else if (i % 3 == 0) {
                os.push_back("Fizz");}
            else if (i % 5 == 0) {
                os.push_back("Buzz");}
            else 
                {os.push_back(to_string(i));}
        }
        return os;
    }
}; 

Upvotes: 0

Related Questions