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

 

코딩테스트 연습 - [1차] 다트 게임

 

programmers.co.kr

<풀이>

1. 주어진 문자열에서 총 3게임의 점수를 구한다.

2. 각 1게임 마다 점수, 보너스, 옵션을 분리해서 해당 게임의 점수를 계산한다.

3. 3게임 점수의 합을 반환한다.

 

<해법>

특별한 아이디어가 필요없는 문제라고 생각합니다. 문자열을 하나하나 분리해 나가면서, 주어진 방법에 따라 계산하는 방식으로 구현하였습니다. 주어진 점수 계산 방법을 정확하게 구현하는 것이 이 문제의 핵심이라고 생각합니다.

 

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <string>
 
using namespace std;
 
//3게임 점수
int scores[3];
 
int solution(string dartResult) {
    int answer = 0;
 
    //문자열 index
    int index = 0;
 
    //각 게임마다 점수 구하기
    for (int i = 0; i < 3; i++) {
 
        //1. 점수
        int score;
        if (dartResult[index] == '1' && dartResult[index + 1== '0') { //점수가 10일 경우
            score = 10;
            index++;
        }
        else { //그 외
            score = dartResult[index] - '0';
        }
        scores[i] = score;
        index++;
 
        //2. 보너스
        char bonus;
        switch (dartResult[index]) {
        case 'S': scores[i] = scores[i] * 1break;
        case 'D': scores[i] = scores[i] * scores[i]; break;
        case 'T': scores[i] = scores[i] * scores[i] * scores[i]; break;    
        }
        index++;
 
        //3. 옵션
        char option;      
        if (dartResult[index] == '*') {
            if (i != 0) { //첫 게임이 아닐 경우
                scores[i - 1*= 2;
            }
            scores[i] *= 2;
        }
        else if (dartResult[index] == '#') {
            scores[i] *= -1;
        }
        else { //옵션이 없을 경우
            continue;
        }
        index++;
 
    }
 
    //점수 합계
    for (int i = 0; i < 3; i++) {
        answer += scores[i];
    }
 
    //결과 반환
    return answer;
}
 

 

문자열과 구현에 대해 알아볼 수 있는 문제였습니다.

+ Recent posts