본문 바로가기

Programming/알고리즘

[백준] 1330 - 두 수 비교하기 -JAVA[자바]

 

위의 내용은 단순 비교로 끝낼 수 있다.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        StringTokenizer st = (new StringTokenizer(br.readLine(), " "));
        int a = Integer.parseInt(st.nextToken());
        int b = Integer.parseInt(st.nextToken());
        
        if (a>b){
            System.out.print(">");
        } else if (a==b){
            System.out.print("==");
        } else {
            System.out.print("<");
        }
    }
}

 

정말 간단한 문제이지만, 더 간단하게 만들 수 있는 

"삼항 연산자" 를 배워보자

 

삼항 연산자란,

변수 = (조건문) ? (true 일 때의 연산) : (false 일 때의 연산) ;

 

로 나타낼 수 있다.  식만 봐서는 '뭐지..?' 싶다.

 

위의 문제를 삼항 연산자로 나타내면,

String result = (a>b) ? ">" : (a<b) ? "<" : "==";

로 나타낼 수 있다.

 

a>b 가 true 일 때 ">" 라는 문자열을 result 에 저장하는데, 
여기서는 조건이 3가지 이므로 (if - else if - else)

false 일 경우 삼항연산자를 한 번 더 중첩하면 else fi의 역할을 하게 된다.

즉, a<b 라는 조건식에 대해 검사하여 true 일 때와 false 일 때의 연산을 해주면 된다!

 

더 간단히 쓴다면, 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        StringTokenizer st = (new StringTokenizer(br.readLine(), " "));
        int a = Integer.parseInt(st.nextToken());
        int b = Integer.parseInt(st.nextToken());
        
        System.out.print((a>b) ? ">" :(a<b) ? "<": "==");
    }
}

 

로 간단히 한 줄로 나타낼 수 있다.

 

 

 

두 코드의 속도는 크게 변하지 않는다.

가독성 면에서 이점이 있다.