Post

[Programmers] #120902 - 문자열 계산하기 [Java][C++][Python]

[Programmers] #120902 - 문자열 계산하기 [Java][C++][Python]

문제 링크


1. 아이디어

덧셈과 뺄셈만 있는 문자열 수식의 값을 구하는 문제다. 연산자가 +와 -뿐이라 우선순위를 따질 필요 없이 앞에서부터 수를 하나씩 더하거나 빼며 누적하면 된다. 수와 연산자가 항상 공백 하나로 구분되어 있어 공백 기준으로 나누면 곧바로 수와 연산자 토큰이 된다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.*;

class Solution {
    public int solution(String my_string) {
        StringTokenizer st = new StringTokenizer(my_string);
        int ans = Integer.parseInt(st.nextToken());

        while (st.hasMoreTokens()) {
            String op = st.nextToken();
            if (op.equals("+")) {
                ans += Integer.parseInt(st.nextToken());
            } else {
                ans -= Integer.parseInt(st.nextToken());
            }
        }

        return ans;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>
using namespace std;

int solution(string my_string) {
    stringstream ss(my_string);
    int ans, x;
    char op;

    ss >> ans;
    while (ss >> op >> x) {
        ans += op == '+' ? x : -x;
    }

    return ans;
}
1
2
def solution(my_string):
    return sum(map(int, my_string.replace("+ ", "").replace("- ", "-").split()))

"+ "를 지우고 "- "를 "-"로 바꿔 뺄셈을 음수 항으로 만든 뒤 전부 더했다.


This post is licensed under CC BY 4.0 by the author.