1,题目要求
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"
]
编写一个程序,输出从1到n的数字的字符串表示。
但是对于三倍的倍数,它应输出“Fizz”而不是数字,并输出五个输出“Buzz”的倍数。 对于三个和五个输出“FizzBuzz”的倍数的数字。
2,题目思路
对于这道题,在3倍、5倍、3倍且5倍的情况下, 输出对应的单词(行酒令)。
这道题也很简单,最简单的就是直接利用if和else操作来依次判断。不过根据题目,我们还可以对if进行优化,只需要先对3的倍数进行判断,再对5的倍数进行判断即可。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> res;
for(int i = 1;i<=n;i++){
string tmp = "";
if(i % 3 == 0)
tmp += "Fizz";
if(i % 5 == 0)
tmp += "Buzz";
if(tmp.empty())
tmp = to_string(i);
res.push_back(tmp);
}
return res;
}
};