给你一个整数 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"]
leetcode代码
cpp
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> answer(n);
for(int i=0;i<n;i++){
if((i+1)%3==0&&(i+1)%5==0)
answer[i]="FizzBuzz";
else if((i+1)%3==0)
answer[i]="Fizz";
else if((i+1)%5==0)
answer[i]="Buzz";
else
answer[i]=to_string(i+1);
}
return answer;
}
};
总的来说,这道题的思路比较简单,就是模拟+字符串,但需要注意的点很多,比如声明动态数组时必须指定大小,否则不能对answer[i]进行赋值,只能使用push_back或者emplace_back添加元素。并且数组下标从零开始,因此我们要对i+1做判断。