412. Fizz Buzz
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == “FizzBuzz” if i is divisible by 3 and 5.
answer[i] == “Fizz” if i is divisible by 3.
answer[i] == “Buzz” if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.
Example 1:
Input: n = 3
Output: [“1”,“2”,“Fizz”]
Example 2:
Input: n = 5
Output: [“1”,“2”,“Fizz”,“4”,“Buzz”]
Example 3:
Input: n = 15
Output: [“1”,“2”,“Fizz”,“4”,“Buzz”,“Fizz”,“7”,“8”,“Fizz”,“Buzz”,“11”,“Fizz”,“13”,“14”,“FizzBuzz”]
Constraints:
1 <= n <= 104
solution1模拟+字符串拼接
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;
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/fizz-buzz/solution/fizz-buzz-by-leetcode-solution-s0s5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string>ans;
for(int i=1;i<=n;i++){
if(i%3==0 && i%5==0){
ans.push_back("FizzBuzz");
}else if(i%3==0){
ans.push_back("Fizz");
}else if(i%5==0){
ans.push_back("Buzz");
}else{
ans.push_back(to_string(i));
}
}
return ans;
}
};
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> v;
v.reserve(n);
for (int i = 1; i <= n; i++)
v.emplace_back(i % 3 ? (i % 5 ? to_string(i) : "Buzz") : (i % 5 ? "Fizz" : "FizzBuzz"));
return v;
}
};
作者:inue
链接:https://leetcode.cn/problems/fizz-buzz/solution/jian-dan-ti-zhong-quan-chu-ji-by-inue-pltx/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。