mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
add 412. Fizz Buzz 🍺
This commit is contained in:
parent
45a0520e00
commit
662ee82959
@ -278,6 +278,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。
|
||||
| 404 |[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/404.%20Sum%20of%20Left%20Leaves.md)|Easy| |
|
||||
| 405 |[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/405.%20Convert%20a%20Number%20to%20Hexadecimal.md)|Easy| |
|
||||
| 409 |[Longest Palindrome](https://leetcode.com/problems/longest-palindrome)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/409.%20Longest%20Palindrome.md)|Easy| |
|
||||
| 412 |[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/)|[C++](solutions/412.%20Fizz%20Buzz.md)|Easy| |
|
||||
| 414 |[Third Maximum Number](https://leetcode.com/problems/third-maximum-number)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/414.%20Third%20Maximum%20Number.md)|Easy| |
|
||||
| 415 |[Add Strings](https://leetcode.com/problems/add-strings)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/415.%20Add%20Strings.md)|Easy| |
|
||||
| 416 |[Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/416.%20Partition%20Equal%20Subset%20Sum.md)|Medium| |
|
||||
|
51
solutions/412. Fizz Buzz.md
Normal file
51
solutions/412. Fizz Buzz.md
Normal file
@ -0,0 +1,51 @@
|
||||
# [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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user