问题描述:
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”.
思路:这道题目非常简单,只需要判断一个数是否是3、5、15的倍数即可。但是有一个小tips, 在判断的时候下判断是否是15的倍数再判断其他的会更快一些。
代码:
import java.util.ArrayList;
import java.util.List;
/**
* @author 作者 : xcy
* @version 创建时间:2016年10月21日 下午9:37:54
* leetcode 412
*/
public class t412 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public static List<String> fizzBuzz(int n) {
List<String> re = new ArrayList<String>();
for (int i = 0; i < n; i++) {
re.add(change(i + 1));
}
return re;
}
public static String change(int n) {
if (n % 15 == 0) {
return "FizzBuzz";
}
if (n % 5 == 0) {
return "Buzz";
}
if (n % 3 == 0) {
return "Fizz";
}
return n + "";
}
}