LeetCode 412. Fizz Buzz

时间:2023-12-16 12:27:20

Problem:

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 = , Return:
[
"",
"",
"Fizz",
"",
"Buzz",
"Fizz",
"",
"",
"Fizz",
"Buzz",
"",
"Fizz",
"",
"",
"FizzBuzz"
]

思路较为简单,首先考虑是否为15的倍数,然后考虑3,5的倍数,然后分情况处理即可。

runtime主要受int to string的影响。期初使用stringstream的方法,后换为C++ 11提供的to string。

class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> re;
for(int i = ; i <= n; i++) {
if (i % == )
re.push_back("FizzBuzz");
else if(i % == )
re.push_back("Fizz");
else if(i % == )
re.push_back("Buzz");
else
{
//stringstream ss;
//ss << i;
//re.push_back(ss.str());
re.push_back(to_string(i));
}
}
return re;
}
};