Fizz Buzz

问题

Given number n. Print number from 1 to n. But:

when number is divided by 3, print "fizz".
when number is divided by 5, print "buzz".
when number is divided by both 3 and 5, print "fizz buzz".
Have you met this question in a real interview? Yes
Example
If n = 15, you should return:

[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz", "11", "fizz",
"13", "14", "fizz buzz"
]

分析

如果使用if-else判断会非常简单,代码演示的是尽量少的使用if-else,个人感觉效率应该差不多。

代码

class Solution {
    /**
     * param n: As description.
     * return: A list of strings.
     */
    public ArrayList fizzBuzz(int n) {
        ArrayList results = new ArrayList();
        int times3=1;
        int times5=1;
        int i=1;
        while(i<=n){
            while(i<=n&&i<3*times3&&i<5*times5){
                results.add(String.valueOf(i));
                i++;
            }
            if(i<=n&&3*times3==5*times5){
                results.add("fizz buzz");
                times3++;
                times5++;
                i++;
                continue;
            }
            while(i<=n&&i>=3*times3){
                results.add("fizz");
                times3++;
                i++;
            }
            while(i<=n&&i>=5*times5){
                results.add("buzz");
                times5++;
                i++;
            }
        }
        return results;
    }
}

你可能感兴趣的:(Fizz Buzz)