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

Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]
大致意思是输出一1-n的数其中3的倍数用fizz代替,5的倍数用buzz代替,15的倍数用FizzBuzz代替
循环即可
public List<String> fizzBuzz(int n) {
        List<String> result = new ArrayList<String>();
        for(int i=1;i<=n;i++)
        {
            if(i%3==0)
            {
                if(i%15==0)
                {
                    result.add("FizzBuzz");
                }
                else
                {
                     result.add("Fizz");
                }
            }
            else if(i%5==0)
            {
                result.add("Buzz");
            }
            else
            {
                result.add(String.valueOf(i));
            }
        }
        return result;
    }

还有一种思路,考虑到取余的效率比较低,可以维护两个变量,一个到了3输出fizz然后归0,一个到了5输出buzz然后归0。如果同时到了3和5则输出FizzBuzz,代码很简单不写了

posted @ 2018-01-05 19:50  icychen  阅读(266)  评论(0编辑  收藏  举报