LeetCode/solutions/412. Fizz Buzz.md
2020-03-23 12:01:40 +08:00

51 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [412. Fizz Buzz](https://leetcode.com/problems/fizz-buzz/)
# 思路
这题很简单我们可以用for循环从i=1到i=n然后判断i是否是3或者5的倍数。
评论区说因为取余操作`%`比较费时,所以我们应该避免取余,下面代码给出了两种避免取余的思路,亲测确实比直接取余要快一点点。
# C++
``` C++
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string>res(n);
for(int i = 1; i <= n; i++) res[i-1] = to_string(i);
for(int i = 2; i < n; i+=3) res[i] = "Fizz";
for(int i = 4; i < n; i+=5) res[i] = "Buzz";
for(int i = 14; i < n; i+=15) res[i] = "FizzBuzz";
return res;
}
};
```
``` C++
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string>res(n);
int fizz = 3, buzz = 5;
for(int i = 1; i <= n; i++){
if(i == fizz){
res[i-1] = "Fizz";
fizz += 3;
if(i == buzz){
buzz += 5;
res[i-1] += "Buzz";
}
}
else if(i == buzz){
buzz += 5;
res[i-1] = "Buzz";
}
else res[i-1] = to_string(i);
}
return res;
}
};
```