Reputation:
I am new to C++ and wrote the following:
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> result(n);
for (int i=1;i<=n;++i)
{
if (i%3==0 and i%5==0)
result[i-1]="FizzBuzz";
else if (i%3==0)
result[i-1]="Fizz";
else if (i%5==0)
result[i-1]="Buzz";
else result[i-1]=""+i;
}
return result;
}
};
when the input is 1 I am getting overflow error, why is that? the last line seems the problem but I think it's totally fine.
Upvotes: 0
Views: 80
Reputation: 409364
The expression ""+i
doesn't convert the integer value in i
to a string. Instead it's the same as &(("")[i])
. I.e. it's a pointer to the i:th value of the string ""
. Which is out of bounds since the empty string only have a single element at index 0
(the string terminator).
Use std::to_string
instead:
result[i-1]=std::to_string(i);
Upvotes: 1