LeetCode | 412. Fizz Buzz

来源:互联网 发布:veket linux img 编辑:程序博客网 时间:2024/06/01 10:23

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;    }}
0 0