Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15,
Return:
[
“1”,
“2”,
“Fizz”,
“4”,
“Buzz”,
“Fizz”,
“7”,
“8”,
“Fizz”,
“Buzz”,
“11”,
“Fizz”,
“13”,
“14”,
“FizzBuzz”
]
class Solution {
public:
vector<string> fizzBuzz(int n) {
//int i=0;
vector<string> str;
bool mark3=false;
bool mark5=false;
for(int i=1;i<=n;i++)
{
if(i%3==0) mark3=true;
else mark3=false;
if(i%5==0) mark5=true;
else mark5=false;
if(mark3&&mark5)
{
str.push_back("FizzBuzz");
}
else if(mark3)
{
str.push_back("Fizz");
}
else if(mark5)
{
str.push_back("Buzz");
}
else
{
str.push_back(to_string(i));
}
}
return str;
}
};
注意,把int转成string可以使用to_string();也可以使用stringstream
可以把stringstream视作一个容器,吃掉一个变量后吐出一个变量。
stringstream ss;
int a=1;
ss<
class Solution {
public:
vector<string> fizzBuzz(int n) {
//int i=0;
vector<string> str;
string temp;
bool mark3=false;
bool mark5=false;
for(int i=1;i<=n;i++)
{
if(i%3==0) mark3=true;
else mark3=false;
if(i%5==0) mark5=true;
else mark5=false;
if(mark3&&mark5)
{
str.push_back("FizzBuzz");
}
else if(mark3)
{
str.push_back("Fizz");
}
else if(mark5)
{
str.push_back("Buzz");
}
else
{
stringstream ss;
ss<<i;
temp=ss.str();
str.push_back(temp);
}
}
return str;
}
};
但是第二中方法要慢一些,不然to_string()