LeetCode | 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”.


創建兩個整數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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章