코딩테스트/Java

(2018 카카오) [1차] 다트게임 Java

SK_MOUSE 2020. 12. 30. 11:30

https://programmers.co.kr/learn/courses/30/lessons/17682

 

어렵지 않은 문제였다.

 

Stack을 이용해서 push pop으로 불러와서 연산하면 되는 문제이다.

 

switch문으로 시도했는데 잘 안돼서 if문으로 수정하여 풀이했다.

예외케이스로 숫자의 값은 0~10 사이인데, charAt으로 불러오는 과정에서, 10이면 1다음에 0을 더 불러와야되므로 체크하는 과정이 필요했다.

import java.util.Stack; class Solution { ​​​​public int solution(String dartResult) { ​​​​​​​​int answer = 0; ​​​​​​​​Stack<Integer> stack = new Stack<>(); ​​​​​​​​for (int i = 0; i < dartResult.length(); i++) { ​​​​​​​​​​​​char input = dartResult.charAt(i); ​​​​​​​​​​​​int num; ​​​​​​​​​​​​if (input == 'S') { ​​​​​​​​​​​​​​​​//아무것도 안해도됨. ^1 ​​​​​​​​​​​​} else if (input == 'D') { ​​​​​​​​​​​​​​​​num = stack.pop(); ​​​​​​​​​​​​​​​​stack.push(num * num);//^2 ​​​​​​​​​​​​} else if (input == 'T') { ​​​​​​​​​​​​​​​​num = stack.pop(); ​​​​​​​​​​​​​​​​stack.push(num * num * num);//^3 ​​​​​​​​​​​​} else if (input == '*') { ​​​​​​​​​​​​​​​​num = stack.pop(); ​​​​​​​​​​​​​​​​if (!stack.isEmpty()) {//두개 뽑아서 *2해주는경우 ​​​​​​​​​​​​​​​​​​​​stack.push(stack.pop() * 2); ​​​​​​​​​​​​​​​​​​​​stack.push(num * 2); ​​​​​​​​​​​​​​​​} else {//첫번째 뽑힌경우(stack이 비어있는경우) ​​​​​​​​​​​​​​​​​​​​stack.push(num * 2); ​​​​​​​​​​​​​​​​} ​​​​​​​​​​​​} else if (input == '#') { ​​​​​​​​​​​​​​​​num = stack.pop(); ​​​​​​​​​​​​​​​​stack.push(num * (-1)); ​​​​​​​​​​​​} else { ​​​​​​​​​​​​​​​​num = input - '0'; ​​​​​​​​​​​​​​​​if(dartResult.charAt(i)=='1'&&dartResult.charAt(i+1)=='0'){ ​​​​​​​​​​​​​​​​​​​​i+=1; ​​​​​​​​​​​​​​​​​​​​num=10; ​​​​​​​​​​​​​​​​} ​​​​​​​​​​​​​​​​stack.push(num); ​​​​​​​​​​​​} ​​​​​​​​} ​​​​​​​​while (!stack.isEmpty()) { ​​​​​​​​​​​​System.out.println(stack.peek()); ​​​​​​​​​​​​answer += stack.pop(); ​​​​​​​​} ​​​​​​​​return answer; ​​​​} }

 

 

반응형