《LeetCode之每日一题》:177.Fizz Buzz
Posted 是七喜呀!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《LeetCode之每日一题》:177.Fizz Buzz相关的知识,希望对你有一定的参考价值。
题目链接: Fizz Buzz
有关题目
给你一个整数 n ,找出从 1 到 n 各个整数的 Fizz Buzz 表示,
并用字符串数组 answer(下标从 1 开始)返回结果,其中:
answer[i] == "FizzBuzz" 如果 i 同时是 3 和 5 的倍数。
answer[i] == "Fizz" 如果 i 是 3 的倍数。
answer[i] == "Buzz" 如果 i 是 5 的倍数。
answer[i] == i 如果上述条件全不满足。
示例 1:
输入:n = 3
输出:["1","2","Fizz"]
示例 2:
输入:n = 5
输出:["1","2","Fizz","4","Buzz"]
示例 3:
输入:n = 15
输出:["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz",
"11","Fizz","13","14","FizzBuzz"]
提示:
1 <= n <= 10^4
题解
法一:模拟
代码一:
参考官方题解
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> answer;
for (int i = 1; i <= n; i++)
{
string curr;
if (i % 3 == 0)
curr += "Fizz";
if (i % 5 == 0)
curr += "Buzz";
if (curr.size() == 0)
curr += to_string(i);
answer.emplace_back(curr);
}
return answer;
}
};
代码二:
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> answer;
for (int i = 1; i <= n; i++)
{
string curr;
if (i % 15 == 0)
curr += "FizzBuzz";
else if (i % 3 == 0)
curr += "Fizz";
else if (i % 5 == 0)
curr += "Buzz";
else
curr += to_string(i);
answer.emplace_back(curr);
}
return answer;
}
};
代码三:
参考官方题解评论区下Kuroko
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> answer(n);
int i;
for (i = 1; i <= n; i++) answer[i - 1] = to_string(i);
for (i = 3; i <= n; i += 3) answer[i - 1] = "Fizz";
for (i = 5; i <= n; i += 5) answer[i - 1] = "Buzz";
for (i = 15; i <= n; i += 15) answer[i - 1] = "FizzBuzz";
return answer;
}
};
以上是关于《LeetCode之每日一题》:177.Fizz Buzz的主要内容,如果未能解决你的问题,请参考以下文章