412. Fizz Buzz

  • 58.%

https://leetcode.com/problems/fizz-buzz/

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Example:

n = 15,

Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]

方法一:

我的代码实现:

Oct 16, 2017

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> res;
for(int i=1; i<=n; i++){
if(i%3==0 && i%5==0)
res.push_back("FizzBuzz");
else if(i%3 == 0)
res.push_back("Fizz");
else if(i%5 == 0)
res.push_back("Buzz");
else
res.push_back(to_string(i));
}
return res;
}
};

6ms, October 17, 2016

https://discuss.leetcode.com/topic/62160/pretty-straightforward-cpp-solution

注意,使用to_string(i)来把int转化为string

此处用15表示同时被3和5整除的数字,不错的想法。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> res;
for(int i=1; i<=n; i++){
if(i%15 == 0) res.push_back("FizzBuzz");
else if(i%3 == 0) res.push_back("Fizz");
else if(i%5 == 0) res.push_back("Buzz");
else res.push_back(to_string(i));
}
return res;
}
};

python

78ms, October 17, 2016

https://discuss.leetcode.com/topic/63360/python-1-line-solution

1
2
3
4
5
6
7
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
return [str(i) if (i%3 != 0 and i%5 != 0) else (('Fizz'*(i%3==0)) + ('Buzz'*(i%5==0))) for i in range(1, n+1)]

java

4ms, October 17, 2016

https://discuss.leetcode.com/topic/62081/java-easy-iterative-solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public List<String> fizzBuzz(int n) {
List<String> list = new ArrayList<>();
for(int i=1; i<=n; i++){
if(i%3==0 && i%5==0)
list.add("FizzBuzz");
else if(i%3 ==0)
list.add("Fizz");
else if(i%5==0)
list.add("Buzz");
else
list.add(String.valueOf(i));
}
return list;
}
}
谢谢你,可爱的朋友。