문제 출처 사이트 : https://www.acmicpc.net/problem/14681

문제


흔한 수학 문제 중 하나는 주어진 점이 어느 사분면에 속하는지 알아내는 것이다. 사분면은 아래 그림처럼 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 중 하나)를 출력한다.

작성코드


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int firstNum = sc.nextInt();
        int secondNum = sc.nextInt();
        
        sc.close();

        int firstNumCheck = Integer.signum(firstNum);
        int secondNumCheck = Integer.signum(secondNum);

        if(firstNumCheck == 1 && secondNumCheck == 1) System.out.println("1");
        if(firstNumCheck == -1 && secondNumCheck == 1) System.out.println("2");
        if(firstNumCheck == -1 && secondNumCheck == -1) System.out.println("3");
        if(firstNumCheck == 1 && secondNumCheck == -1) System.out.println("4");

    }
}

문제 풀이 과정


양수인지 음수인지에 대해 체크 하기 위한 방법 중 가장 쉬운것은 0 과 비교 하는 것이 가장 편리합니다.

그런데 Java 언어 측에서 양수와 음수를 체크 해주는 Method가 혹시 있을까 해서 찾아봤습니다. Math.signum() , Intger.signum()을 확인 할 수 있었고, 이를 활용해서 문제를 풀었습니다.

Math.signum() 은 float 과 double 값에만 작동합니다.
Return : 인수의 부호 함수를 반환합니다. 인수가 0이면 0, 인수가 0보다 크면 1.0, 인수가 0보다 작으면 -1.0입니다.

Intger.signum() 은 int 형식에서 작동합니다.
Return : 지정된 값이 음수이면 반환 값은 -1, 지정된 값이 0이면 0, 지정된 값이 양수이면 1입니다.

참고사이트


 

https://stackoverflow.com/questions/19766051/java-check-if-input-is-a-positive-integer-negative-integer-natural-number-an

 

Java - Check if input is a positive integer, negative integer, natural number and so on.

Is there any in-built method in Java where you can find the user input's type whether it is positive, or negative and so on? The code below doesn't work. I am trying to find a way to input any in-b...

stackoverflow.com

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#signum(int) 

 

Integer (Java Platform SE 7 )

Returns the value obtained by rotating the two's complement binary representation of the specified int value left by the specified number of bits. (Bits shifted out of the left hand, or high-order, side reenter on the right, or low-order.) Note that left r

docs.oracle.com

https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#signum%28double%29

'Java > 백준 알고리즘' 카테고리의 다른 글

[BAEKJOON] 2884 알람 시계  (0) 2021.10.03
[BAEKJOON] 2588 곱셈  (0) 2021.10.02

+ Recent posts