题目 “Fizz Buzz”
Given number n. Print number from 1 to n. But:
when number is divided by 3, print “fizz”.
when number is divided by 5, print “buzz”.
when number is divided by both 3 and 5, print “fizz buzz”.
Example
If n = 15, you should return:
[
“1”, “2”, “fizz”,
“4”, “buzz”, “fizz”,
“7”, “8”, “fizz”,
“buzz”, “11”, “fizz”,
“13”, “14”, “fizz buzz”
]
Challenge
Can you do it with only one if statement?
源代码:
class Solution {
public:
/**
* @param n: An integer
* @return: A list of strings.
*/
vector<string> fizzBuzz(int n) {
// write your code here
vector<string> content;
for(int i=1;i<=n;i++)
{
// cout<<atoi(i.c_str())<<endl;
if((i%3==0)&&(i%5==0))
{
content.push_back("fizz buzz");
continue;
}
else if(i%3==0)
{
content.push_back("fizz");
continue;
}
else if(i%5==0)
{
content.push_back("buzz");
continue;
}
else
{
content.push_back(std::to_string(i));
}
}
return content;
}
};