티스토리 뷰

문제출처 - https://programmers.co.kr/learn/courses/30/lessons/17682

 

코딩테스트 연습 - [1차] 다트 게임 | 프로그래머스

 

programmers.co.kr

카카오 문제는 레벨1도 쉽지 않은 것 같다..

#include <string>
#include <cmath>
using namespace std;

int solution(string dartResult) {
    int answer = 0;
    int temp[3] = {0,};
    int cnt = 0;
    
    for(int i=0; i<dartResult.size();) {
        
        if(dartResult[i] >= 48 && dartResult[i] <= 57) {
            // 숫자가 10인 경우 예외처리
            if(dartResult[i+1] == '0') {
                temp[cnt] = 10;
                i += 2;
                cnt++;
                continue;
            }
            temp[cnt] = dartResult[i] - '0';
            cnt++;
        } 
        else if (dartResult[i] == 'S') {
            temp[cnt-1] = pow(temp[cnt-1], 1);
        } else if (dartResult[i] == 'D') {
            temp[cnt-1] = pow(temp[cnt-1], 2);
        } else if (dartResult[i] == 'T') {
            temp[cnt-1] = pow(temp[cnt-1], 3);
        } 
        else if (dartResult[i] == '*') {
            temp[cnt-1] *= 2;
            temp[cnt-2] *= 2;
        } 
        else if (dartResult[i] == '#') {
            temp[cnt-1] = temp[cnt-1] * (-1);
        }
        i++;
    }
    
    for(int i=0; i<3; i++) {
        answer += temp[i];
    }
    
    return answer;
}

풀이

 

가장 단순하게 풀었다.

 

숫자면 배열에 저장해놓고 문자면 문자에 맞게 처리해줬다.

 

숫자가 0~9까지만 존재하는게 아니라 10도 있기 때문에 이 경우는 예외처리를 해줬다. 10이라는 숫자 때문에 for문에 변화식을 쓰지 않았다.

 

temp[cnt-1]에서 cnt에 1씩 뺀 이유는 맨 위에서 숫자인 경우 처리를 하고 cnt++을 해줬기 때문이다. 만약 cnt-1을 하지 않는다면 계산값이 0이 될 것이다.

 

마지막에 배열에 있는 값들을 다 더해주면 끝

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함