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”.
public class Solution{
public List<String> fizzBuzz(int n){
List<String> list = new ArrayList<String>(n);
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;
}
}
这题很简单,题目的意思是,在1~n,3的倍数,5的倍数,3和5的倍数分别输出相应的字符串,那很容易想到用取余运算解决。稍微要注意就是要把限定条件中范围小的放前面,比如 (i % 3 == 0 && i % 5 == 0)。