기본 콘텐츠로 건너뛰기

프로그래머스 - 최대값과 최소값

import java.util.Vector;

public class GetMinMaxString {
    public String getMinMaxString(String str) {
        Integer min=Integer.MAX_VALUE,max=Integer.MIN_VALUE;
        String[] sepstr = str.split(" ");
        Vector<Integer> vec = new Vector<Integer>();
        for(int i=0;i<sepstr.length;i++) {
            vec.addElement(Integer.parseInt(sepstr[i]));
        }
        for(int i=0;i<vec.size();i++) {
            if(vec.get(i)<min) {
                min = vec.get(i);
            }
            if(vec.get(i) > max) {
                max = vec.get(i);
            }
        }

        return min+" "+max;
    }

    public static void main(String[] args) {
        String str = "1 2 3 4";
        GetMinMaxString minMax = new GetMinMaxString();
        //아래는 테스트로 출력해 보기 위한 코드입니다.
        System.out.println("최대값과 최소값은?" + minMax.getMinMaxString(str));
    }
}

아래와 같은 풀이가 있었다. 괜찮은 방법인거 같다.
public class GetMinMaxString {
    public String getMinMaxString(String str) {
        String[] tmp = str.split(" ");
        int min, max, n;
        min = max = Integer.parseInt(tmp[0]);
        for (int i = 1; i < tmp.length; i++) {
                n = Integer.parseInt(tmp[i]);
            if(min > n) min = n;
            if(max < n) max = n;
        }

        return min + " " + max;

    }

    public static void main(String[] args) {
        String str = "1 2 3 4";
        GetMinMaxString minMax = new GetMinMaxString();
        //아래는 테스트로 출력해 보기 위한 코드입니다.
        System.out.println("최대값과 최소값은?" + minMax.getMinMaxString(str));
    }
}

댓글

이 블로그의 인기 게시물

프로그래머스 - 시저 암호

public class Caesar { String caesar ( String s , int n ) { n %= 26 ; String result = "" ; char [] temp = s . toCharArray (); for ( int i = 0 ; i < temp . length ; i ++) { if ( temp [ i ]>= 'a' && temp [ i ]<= 'z' ) temp [ i ] = ( char ) (( temp [ i ]+ n )> 'z' ? ( temp [ i ]+ n - 1 )% 'z' + 'a' : ( temp [ i ]+ n )); else if ( temp [ i ]>= 'A' && temp [ i ]<= 'Z' ) temp [ i ] = ( char ) (( temp [ i ]+ n )> 'Z' ? ( temp [ i ]+ n - 1 )% 'Z' + 'A' : ( temp [ i ]+ n )); result += temp [ i ]; } return result ; } public static void main ( String [] args ) { Caesar c = new Caesar (); System . out . println ( "s는 'a B z', n은 4인 경우: " + c . caesar ( ...