9. Fizz Buzz

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/foradawn/article/details/79948733

9. Fizz Buzz

Description

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

Example

If n = 15, you should return:
[
  "1", "2", "fizz",
  "4", "buzz", "fizz",
  "7", "8", "fizz",
  "buzz", "11", "fizz",
  "13", "14", "fizz buzz"
]

Solution

public class Solution {
    /**
     * @param n: An integer
     * @return: A list of strings.
     */
    public List<String> fizzBuzz(int n) {
        // write your code here
        ArrayList<String> list = new ArrayList<String>();
        for(int i=1;i<=n;i++){
            if(i%3==0 && i%5==0) list.add("fizz buzz");
            else if(i%3==0) list.add("fizz");
            else if(i%5==0) list.add("buzz");
            else list.add(i+"");
        }
        return list;
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页