Leetcode412. Fizz Buzz

来源:互联网 发布:网络暴力的案例 编辑:程序博客网 时间:2024/05/17 21:54

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;    }
原创粉丝点击