Lintcode: Fizz Buzz

4034 단어 code
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"]

StringBuffer의 사용법, append 방법의 매개 변수는boolean,char,char[],CharSequence,double,float,int,long,String,StringBuffer를
 1 class Solution {

 2     /**

 3      * param n: As description.

 4      * return: A list of strings.

 5      */

 6     public ArrayList<String> fizzBuzz(int n) {

 7         ArrayList<String> res = new ArrayList<String>();

 8         for (int i=1; i<=n; i++) {

 9             StringBuffer buf = new StringBuffer();

10             if (i%3==0 && i%5!=0) {

11                 buf.append("fizz");

12             }

13             if (i%3!=0 && i%5==0) {

14                 buf.append("buzz");

15             }

16             if (i%3==0 && i%5==0) {

17                 buf.append("fizz buzz");

18             }

19             if (i%3!=0 && i%5!=0) {

20                 buf.append(i);

21             }

22             res.add(buf.toString());

23         }

24         return res;

25     }

26 }

좋은 웹페이지 즐겨찾기