Computer Engineering/알고리즘 테스트

코드업[3120]-리모컨

말하는호구마 2021. 1. 3. 21:59

 

https://codeup.kr/problem.php?id=3120

 

그리디 문제라고 명시되어 있지만 그리디의 특징을 크게 띄지는 않는듯하다.

 

나의 풀이

import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws Exception {
		Scanner sc=new Scanner(System.in);
		String input=sc.nextLine();
		String str[]=input.split(" ");
		int arr[]=new int[2];
		for(int i=0;i<2;i++) {
			arr[i]=Integer.parseInt(str[i]);
		}
		int answer=0;
		int temp=arr[1]-arr[0];
		while(true) {
			if(temp<0) temp=temp*-1;
			
			if(temp>=10 || (temp<10 && temp>7)) {
				temp-=10;
			}else if(temp<=7&& temp>2){
				temp-=5;
			}else if(temp<=2 && temp>0) {
				temp-=1;
			}else {
				break;
			}
			answer++;
		}
		System.out.println(answer);
	}
		
}

이 문제로 새로 배운점은, 양수와 음수일 때를 구분않고 푸는 법이다.

두 경우를 따로 처리하는 것이 아니라 음수일 때 -1을 곱해주며 항상 양수를 유지하도록 풀면 코드가 훨씬 간결해진다. 

시간이 조금 지체되는 것 같아 최선의 방법은 아닌듯하다.