Post

[Programmers] #181865 - 간단한 식 계산하기 [Java][C++][Python]

[Programmers] #181865 - 간단한 식 계산하기 [Java][C++][Python]

문제 링크


1. 아이디어

a op b” 꼴의 식을 계산한 결과를 반환하는 문제로 공백을 기준으로 파싱만 하면 간단하게 해결할 수 있다.


2. 복잡도

접근시간공간
풀이$O(1)$$O(1)$

3. 코드

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

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

class Solution {
    public int solution(String binomial) {
        StringTokenizer st = new StringTokenizer(binomial);
        int a = Integer.parseInt(st.nextToken());
        String op = st.nextToken();
        int b = Integer.parseInt(st.nextToken());

        if (op.equals("+")) return a + b;
        if (op.equals("-")) return a - b;
        return a * b;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <bits/stdc++.h>
using namespace std;

int solution(string binomial) {
    stringstream ss(binomial);
    int a, b;
    string op;
    ss >> a >> op >> b;

    if (op == "+") return a + b;
    if (op == "-") return a - b;
    return a * b;
}
1
2
3
4
5
6
7
8
9
def solution(binomial):
    a, op, b = binomial.split()
    a, b = int(a), int(b)

    if op == "+":
        return a + b
    if op == "-":
        return a - b
    return a * b

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