给你一个整数n. 从 1 到 n 按照下面的规则打印每个数:
- 如果这个数被3整除,打印
fizz
. - 如果这个数被5整除,打印
buzz
. - 如果这个数能同时被
3
和5
整除,打印fizz buzz
.
思路:
1、使用一个ArrayList数组来保存值
2、当15整除,数组增加记录:add,以下同理
public ArrayList<String> fizzBuzz(int n) { ArrayList<String> results = new ArrayList<String>(); for (int i = 1; i <= n; i++) { if (i % 15 == 0) { results.add("fizz buzz"); } else if (i % 5 == 0) { results.add("buzz"); } else if (i % 3 == 0) { results.add("fizz"); } else { results.add(String.valueOf(i)); } } return results; }