본문 바로가기

프로그래머스/lv0

컨트롤 제트

/* 컨트롤 제트
 * 숫자와 "Z"가 공백으로 구분되어 담긴 문자열이 주어집니다.
 * 문자열에 있는 숫자를 차례대로 더하려고 합니다.
 * 이 때 "Z"가 나오면 바로 전에 더했던 숫자를 뺀다는 뜻입니다.
 * 숫자와 "Z"로 이루어진 문자열 s가 주어질 때, 머쓱이가 구한 값을 return
 *
 * s                result
 * "1 2 Z 3"        4
 * "10 20 30 40"    100
 * "10 Z 20 Z 1"    1
 * "10 Z 20 Z"      0
 * "-1 -2 -3 Z"     -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
public class programmer_0_87 {
    static String a1 = "1 2 Z 3";
    static String a2 = "10 20 30 40";
    static String a3 = "10 Z 20 Z 1";
    static String a4 = "10 Z 20 Z";
    static String a5 = "-1 -2 -3 Z";
    public int solution(String s) {
        int answer = 0;
        String[] ar = s.split(" ");
        for(int i = 0; i < ar.length; i++){
            if(i > 0 && ar[i].equals("Z")){
                answer -= Integer.parseInt(ar[i-1]);
            }
            else{
                answer += Integer.parseInt(ar[i]);
            }
        }
        return answer;
    }    
    public static void main(String args[]){
        programmer_0_87 t = new programmer_0_87();
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1));
        System.out.println("---------------------------------------");
        System.out.println("result2 = " + t.solution(a2));
        System.out.println("---------------------------------------");
        System.out.println("result3 = " + t.solution(a3));
        System.out.println("---------------------------------------");
        System.out.println("result4 = " + t.solution(a4));
        System.out.println("---------------------------------------");
        System.out.println("result5 = " + t.solution(a5));
        System.out.println("---------------------------------------");
    }
}
cs

'프로그래머스 > lv0' 카테고리의 다른 글

유한소수 판별하기  (0) 2022.12.07
직사각형의 넓이  (1) 2022.12.07
삼각형의 완성조건 (2)  (1) 2022.12.07
옹알이(1)  (0) 2022.12.06
다음에 올 숫자  (0) 2022.12.06