您的位置:首页 > 其它

<LeetCode> 412. Fizz Buzz

2017-10-16 19:03 351 查看
412. 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”.
Example:
n = 15,

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


题意:

输出1~n之间的数,其中遇3的倍数输出Fizz,遇5倍数输出Buzz,遇15的倍数输出FizzBuzz。

思路就很简单了

class Solution {
public List<String> fizzBuzz(int n) {
//int n = 50;
List<String> list = new ArrayList<String>();
for (int i = 1; i <= n; i++) {
if(i%3==0&&i%5!=0){
list.add("Fizz");
}else if(i%3!=0&&i%5==0){
list.add("Buzz");
}else if(i%15==0){
list.add("FizzBuzz");
}else {
list.add(Integer.toString(i));
}
}
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: