본문 바로가기
Coding Test/Java Coding Test

[백준알고리즘 / 자바] - 사분면 고르기

by nam_ji 2024. 11. 15.

사분면 고르기 - 브론즈 5

문제

테스트 (인텔리제이)

package 백준;

import java.util.Scanner;

public class 사분면_고르기 {
    public static void main(String[] args) {
        /*
        흔한 수학 문제 중 하나는 주어진 점이 어느 사분면에 속하는지 알아내는 것이다.
        사분면은 아래 그림처럼 1부터 4까지 번호를 갖는다.
        "Quadrant n"은 "제n사분면"이라는 뜻이다.
        예를 들어, 좌표가 (12, 5)인 점 A는 x좌표와 y좌표가 모두 양수이므로 제1사분면에 속한다.
        점 B는 x좌표가 음수이고 y좌표가 양수이므로 제2사분면에 속한다.
        점의 좌표를 입력받아 그 점이 어느 사분면에 속하는지 알아내는 프로그램을 작성하시오. 단, x좌표와 y좌표는 모두 양수나 음수라고 가정한다.

        입력
        첫 줄에는 정수 x가 주어진다.
        (−1000 ≤ x ≤ 1000; x ≠ 0) 다음 줄에는 정수 y가 주어진다. (−1000 ≤ y ≤ 1000; y ≠ 0)

        출력
        점 (x, y)의 사분면 번호(1, 2, 3, 4 중 하나)를 출력한다.

        입력      출력
        12, 5    1
        9, -13   4
         */
        int answer = 0;
        /*
        1 = x, y 둘 다 양수
        2 = x 음수, y 양수
        3 = x, y 둘 다 음수
        4 = x 양수, y 음수
         */
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        int y = in.nextInt();

//        solution1(x, y);
        solution2(x, y);
    }

//    public static void solution1(int x, int y) {
//        if (x > 0 && y > 0) {
//            System.out.println(1);
//        } else if (x < 0 && y > 0) {
//            System.out.println(2);
//        } else if (x < 0 && y < 0) {
//            System.out.println(3);
//        } else {
//            System.out.println(4);
//        }
//    }

    public static void solution2(int x, int y) {
        if (x > 0) {
            if (y > 0) {
                System.out.println(1);
            } else {
                System.out.println(4);
            }
        } else {
            if (y > 0) {
                System.out.println(2);
            } else {
                System.out.println(3);
            }
        }
    }
}

백준알고리즘 코드

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        int y = in.nextInt();

        if (x > 0 && y > 0) {
            System.out.println(1);
        } else if (x < 0 && y > 0) {
            System.out.println(2);
        } else if (x < 0 && y < 0) {
            System.out.println(3);
        } else {
            System.out.println(4);
        }
    }
}

import java.util.*;

public class Main {
    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        int y = in.nextInt();

        solution2(x, y);
    }

    public static void solution2(int x, int y) {
        if (x > 0) {
            if (y > 0) {
                System.out.println(1);
            } else {
                System.out.println(4);
            }
        } else {
            if (y > 0) {
                System.out.println(2);
            } else {
                System.out.println(3);
            }
        }
    }
}