-
프로그래머스 - 다트 게임알고리즘 2024. 5. 1. 15:58
import java.util.*; class Solution { public int solution(String dartResult) { int answer = 0; List<Integer> scores = new ArrayList<>(); StringBuilder sb = new StringBuilder(); int score = 0; for(char c : dartResult.toCharArray()) { if(Character.isDigit(c)) { // 숫자일 때 점수 구하기 sb.append(c); } else if (c == 'S' || c == 'D'|| c == 'T') { // 영역에 따라 계산 score = Integer.parseInt(sb.toString()); sb = new StringBuilder(); // 기존 점수 초기화 if(c == 'S') scores.add(score); else if(c == 'D') scores.add((int) Math.pow(score, 2)); else scores.add((int) Math.pow(score, 3)); } else if (c == '*' || c == '#') { // 옵션 계산 if(scores.size() == 1) { // 첫 시도일 때 옵션 if(c == '*') scores.set(0, scores.get(0) * 2); else scores.set(0, -scores.get(0)); } else if(scores.size() > 1) { // 2, 3번째 시도일 때 옵션 if(c == '*') { scores.set(scores.size() - 1, scores.get(scores.size() - 1) * 2); scores.set(scores.size() - 2, scores.get(scores.size() - 2) * 2); } else { scores.set(scores.size() - 1, -scores.get(scores.size() - 1)); } } } } for(int n : scores) answer += n; return answer; } }
문자열로 입력받기 때문에, 문자열을 toCharArray() 메소드를 이용해 각 문자로 나누어 숫자인지 판단하여 점수와 각 옵션과 영역을 구분했습니다.
점수가 0 ~ 10 이므로 두자리 수가 될 수 있기 때문에 StringBuilder를 사용해서 영역 전까지 점수를 구하고 영역을 입력 받으면 점수를 구해 영역별 보너스 점수를 계산하여 list에 넣었습니다.
이후 옵션이 존재할 수 있기 때문에 옵션에 따라 점수를 계산해주었습니다.
문제를 잘 읽으면 어렵지 않은 문제였는데 지문을 놓쳐 조금 헤맨 문제였습니다.
'알고리즘' 카테고리의 다른 글
프로그래머스 - 완주하지 못한 선수 (0) 2024.05.02 프로그래머스 - 로또의 최고 순위와 최저 순위 (0) 2024.05.02 프로그래머스 - 실패율 (0) 2024.04.29 프로그래머스 - 덧칠하기 (0) 2024.04.29 프로그래머스 - 모의고사 (0) 2024.04.21