[Programmers] #120902 - 문자열 계산하기 [Java][C++][Python]
덧셈과 뺄셈만 등장하는 수식 문자열을 계산해 결과를 구하는 문제.
[Programmers] #120902 - 문자열 계산하기 [Java][C++][Python]
1. 아이디어
수식은 공백으로 구분된 숫자 연산자 숫자 연산자 ... 형태다. 첫 숫자를 초깃값으로 두고 이어지는 연산자 숫자 쌍을 왼쪽부터 차례로 반영한다 — +면 더하고 -면 뺀다. - 뒤의 항을 음수로 보면 부호를 반영한 모든 항의 합으로도 계산할 수 있다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = my_string의 길이)
3. 코드
풀이 [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()))
replace로 "+ "를 지우고 "- "를 "-"로 바꾸면 연산자가 사라지고 각 숫자가 부호를 가진 형태만 남는다. split으로 나눈 뒤 전부 정수로 바꿔 더하면 수식의 값이 된다.
This post is licensed under CC BY 4.0 by the author.