Leetcode412. 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 List<String> fizzBuzz(int n) {
        String a = "Fizz";
        String b = "Buzz";
        List<String> res = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            StringBuilder stringBuilder = new StringBuilder();
            if (i%3==0){
                stringBuilder.append(a);
            }
            if(i%5==0){
                stringBuilder.append(b);
            }
             else if(i%3!=0&&i%5!=0){
                stringBuilder.append(i);
            }
            res.add(stringBuilder.toString());
        }
        return res;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章