Leetcode 412) Fizz Buzz

image

class Solution {
    public List<String> fizzBuzz(int n) {
        List result = new ArrayList();
        for(int i =1;i<=n;i++) {
            String flag="";
            if(i%3==0) {
                flag += "Fizz";
            }

            if(i%5==0) {
                flag+="Buzz";
            }

            if(flag=="") {
                flag += i;
            }

            result.add(flag);
        }
        return result;
    }
}

Check String if it is empty or not?

  1. String empty
  2. Integer.toString, +”” 성능 비교?
  3. 위 아래 시간 뭐가 더 빠른지 비교
public static void main(String[] args){
    int n=20;
    String[] ary=fizzbuzz(n);
    for(int i=0;i<n;i++) {
        System.out.println(ary[i]);
    }

}

private static String[] fizzbuzz(int n){
    String[] result = new String[n];
    for(int i =1;i<=n;i++) {
        String flag="";
        if(i%3==0 && i%5==0) {
            flag= "FizzBuzz";
        }else if(i%5==0) {
            flag="Buzz";
        }else if(i%3==0) {
            flag="Fizz";
        }else{
            flag=""+i;
        }
        result[i-1]=flag;


    }
    return result;
}

image

The second way is faster.


© 2018. All rights reserved.

Powered by Hydejack v8.5.2