티스토리 뷰

출저   https://programmers.co.kr/learn/challenge_codes/125


문제

getMinMaxString 메소드는 String형 변수 str을 매개변수로 입력받습니다. str에는 공백으로 구분된 숫자들이 저장되어 있습니다. str에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 (최소값) (최대값)형태의 String을 반환하는 메소드를 완성하세요. 예를들어 str이 1 2 3 4라면 1 4를 리턴하고, -1 -2 -3 -4라면 -4 -1을 리턴하면 됩니다.


풀이


import java.util.Arrays;

public class GetMinMaxString {
    public String getMinMaxString(String str) {
      String[] arr 	= str.split(" ");
      int[] arrInt 	= new int[arr.length];
      String result = "";
      int len 	= arrInt.length,
    	  i 	= 0;
 			
      for (i = 0; i < len; i++) {
        arrInt[i] = Integer.parseInt(arr[i]);
      }
      
      Arrays.sort(arrInt);
      result = arrInt[0] + " " + arrInt[len - 1];
      
        return result;
    }

    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));
    }
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함