Chapter01. 기본 알고리즘

하파타카·2024년 2월 9일
0
post-thumbnail

연습문제

최대값과 최소값

public class FindMinMax {
    // Chapter01. 기본 알고리즘 - 연습문제
    public static void main(String[] args) {
        System.out.println("max4 = " + max4(3, 19, 2, 7));
        System.out.println("min3 = " + min3(3, 19, 7));
        System.out.println("min4 = " + min4(3, 19, 2, 7));
    }

    // Q01. 네 값의 최댓값을 구하는 max4 메서드를 작성하시오.
    private static int max4(int a, int b, int c, int d) {
        int max = a;
        if (max < b) max = b;
        if (max < c) max = c;
        if (max < d) max = d;

        return max;
    }

    // Q02. 세 값의 최솟값을 구하는 min3 메서드를 작성하시오.
    private static int min3(int a, int b, int c) {
        int min = a;
        if (min > b) min = b;
        if (min > c) min = c;

        return min;
    }

    // Q03. 네 값의 최솟값을 구하는 min4 메서드를 작성하라.
    private static int min4(int a, int b, int c, int d) {
        int min = a;
        if (min > b) min = b;
        if (min > c) min = c;
        if (min > d) min = d;

        return min;
    }
}


실습문제

1C-1

public class Median {
    // Chapter01. 기본 알고리즘 - 실습문제
    public static void main(String[] args) {
        int result = findMedian(1,15,7);
        System.out.println("result = " + result);
    }

    // 1c-1. 3개의 정수값을 입력하고 중앙값을 구하여 출력하라.
    private static int findMedian(int a, int b, int c) {

        if (a > b) {
            if (b > c) {
                return b;
            } else if (a > c){
                return c;
            } else {
                return a;
            }
        } else {
            if (a > c) {
                return a;
            } else if (b > c){
                return c;
            } else {
                return b;
            }
        }
    }
}

1-3

public class JudgeSign {
    public static void main(String[] args) {
        System.out.println(findeJudgeSign(-1));
        System.out.println(findeJudgeSign(0));
        System.out.println(findeJudgeSign(10));
    }

    // 1-3. 입력한 정수값의 부호(양수/음수/0)를 판단하라.
    private static String findeJudgeSign(int a) {
        if (a > 0) {
            return "양수입니다.";
        } else if (a < 0) {
            return "음수입니다.";
        } else {
            return "0입니다.";
        }
    }
}

profile
천 리 길도 가나다라부터

0개의 댓글