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”.
創建兩個整數countThree和countFive,自加加分別等於3或5時,說明該數正是3或5的倍數,並重新置1。
public class Solution {
public List<String> fizzBuzz(int n) {
List<String> list = new ArrayList<String>();
int countThree = 1;
int countFive = 1;
for(int i = 1; i <= n; i++) {
if(countThree != 3 && countFive != 5) {
list.add(String.valueOf(i));
countThree++;
countFive++;
} else if (countThree == 3 && countFive != 5) {
list.add("Fizz");
countThree = 1;
countFive++;
} else if(countThree != 3 && countFive == 5) {
list.add("Buzz");
countFive = 1;
countThree++;
} else {
list.add("FizzBuzz");
countThree = 1;
countFive = 1;
}
}
return list;
}
}