题目来源:
leetcode
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到n输出不同的字符串。
数字是3的倍数时输出Fizz,是5的倍数时输出Buzz,同时是3和5的倍数时输出FizzVBuzz
举例:
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
java写法:
class Solution {
public List<String> fizzBuzz(int n) {
List<String> rev = new ArrayList<String>(n);
for(int i = 1,fizz =0,buzz =0;i<=n;i++)
{
fizz++;
buzz++;
if(fizz ==3 && buzz ==5 )
{
rev.add("FizzBuzz");
fizz=0;
buzz=0;
}
else if(fizz==3)
{
rev.add("Fizz");
fizz=0;
}
else if(buzz==5)
{
rev.add("Buzz");
buzz=0;
}
else
{
rev.add(String.valueOf(i));
}
}
return rev;
}
}
python:
class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]
python这个写法很厉害啊
马上有类似的Java写法如下:
private String FIZZ = "Fizz";
private String BUZZ = "Buzz";
private String FIZZ_BUZZ = "FizzBuzz";
public List<String> fizzBuzz(int n) {
List<String> res = new ArrayList();
for(int i = 1; i <= n; i++){
//remove if else, make code shorter
String temp = i % 15 == 0 ? FIZZ_BUZZ : (i % 3 == 0 ? FIZZ : (i % 5 == 0 ? BUZZ : String.valueOf(i)));
res.add(temp);
}
return res;
}