백준 #4299번 AFC 윔블

jhj·2024년 2월 7일

백준 JAVA

목록 보기
156/583

처음 코드를 짤 때, 아래 코드처럼만 짜면 답이 나올 것이라고 생각하였다.

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int add = sc.nextInt();
		int sub = sc.nextInt();
		int a, b;
		
		a = (add + sub) / 2;
		b = add - a;
		
		System.out.println(a + " " + b);
		sc.close();
	}
}

당당하게 제출하였으나 대차게 틀렸다. 다시 문제를 읽어보니, 그러한 합과 차를 갖는 경기 결과가 없다면 -1을 출력하라는 조건이 있다는 것을 알게 되었다.

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int add = sc.nextInt();
		int sub = sc.nextInt();
		int a, b;
		
		a = (add + sub) / 2;
		b = add - a;
		
		if((add + sub) % 2 == 0) {
			System.out.println(a + " " + b);
		}else {
			System.out.println("-1");
		}
		sc.close();
	}
}

다시 위 코드를 제출하였으나, 다시 틀렸다는 결과를 얻었다. 어떤 것이 문제인지 보니, 차가 합보다 클 경우, 경기 결과가 음수가 나올 수 있다는 것을 알게 되었다.

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int add = sc.nextInt();
		int sub = sc.nextInt();
		int a, b;
		
		a = (add + sub) / 2;
		b = add - a;
		
		if(a >= 0 && b >= 0 && (add + sub) % 2 == 0) {
			System.out.println(a + " " + b);
		}else {
			System.out.println("-1");
		}
		sc.close();
	}
}

최종적으로 위 코드처럼 고쳤다.

profile
개발자를 꿈꾸는

0개의 댓글