[프로그래머스] 다트 게임

Choi Seong Jin·2022년 11월 17일
0

프로그래머스

목록 보기
11/33

문제 링크 : 다트 게임


내 풀이

public int solution(String dartResult) {
        int answer = 0;
        String strNum = "";
        int num = 0;
        int first = 0;
        int second = 0;
        for(int i = 0; i < dartResult.length(); i++){
            if(dartResult.charAt(i) >= '0' && dartResult.charAt(i) <= '9'){
                strNum += dartResult.charAt(i);
            }else{
                if(dartResult.charAt(i) == 'S'){
                    num = Integer.parseInt(strNum);
                    strNum = "";
                    second = first;
                    first = num;
                    answer += first;
                } else if(dartResult.charAt(i) == 'D'){
                    num = Integer.parseInt(strNum);
                    strNum = "";
                    second = first;
                    first = num * num;
                    answer += first;
                } else if(dartResult.charAt(i) == 'T'){
                    num = Integer.parseInt(strNum);
                    strNum = "";
                    second = first;
                    first = num * num * num;
                    answer += first;
                } else if(dartResult.charAt(i) == '*'){
                    answer += first + second;
                    second *= 2;
                    first *= 2;
                } else if(dartResult.charAt(i) == '#'){
                    answer -= first * 2;
                    first *= -1;
                }

            }
        }
        return answer;
    }

조건에 맞게 숫자가 나오면 그 숫자대로 문자열을 변환하고, S, D, T, *, # 에 맞춰서 숫자를 변환했다.
처음 시도는 Stack을 사용해서 변환된 숫자들을 저장하고,* 이나 #이 나오면 Stack에서 pop해서 변환하는 것이었다. 하지만 처음에 *이 나왔을 때 두번 pop하는 과정에서 오류가 발생해 이전까지의 숫자를 first, second에 저장해서 유지하는 방법을 선택했다.
다른 사람들의 풀이를 살펴보니 prev 변수 하나와 Stack을 사용해서 문제를 푸는 것도 존재했다.
확실히 Stack을 사용하려면 스택 단독으로는 힘들 것 같고, 이전 값을 저장하는 변수 또한 하나를 사용해야 한다는 생각이 들었다.

profile
백엔드 개발자 지망생입니다!

0개의 댓글