본문 바로가기
Computer Science

계산기1

by OKOK 2019. 1. 22.

1. 후위표기법

2. 전위표기법

3. 스택 사용법

4. 내용을 구현하기 


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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
 
char infix[10001];
char postfix[10001];
int stack[10001];
int top;
 
void push(int num) 
{
    stack[++top] = num;
}
 
int pop()
{
    return stack[top--];
}
 
int main()
{
    freopen("input.txt""r", stdin);
    int T;
    int length;
    int idx;
    int res;
    int tmp1, tmp2;
    int i;
    for (T = 1; T <= 10++T) {
        top = -1;
        idx = 0;
        res = 0;
        scanf("%d"&length);
        scanf("%s", infix);
        for (i = 0; i < length; ++i) {
            if ((infix[i] >= '0'&& infix[i] <= '9'// 숫자이면,
                postfix[idx++= infix[i]; // 후위 표기법 배열에 넣고
            else if (infix[i] == '+'// 연산자이면,
            {
                while ((top > -1&& (stack[top] == '+')) // 스택에 무엇인가 있고, +가 있다면,
                    postfix[idx++= pop(); // 후위연산자에 +를 넣음
                push(infix[i]); // 그리고 새로운 연산자를 스택에 쌓음
            }
        }
        while (top > -1// 스택에 남아있는 것들을 넘김
            postfix[idx++= pop();
        for (i = 0; i < idx; ++i)
        {
            if ((postfix[i] >= '0'&& (postfix[i] <= '9'))
                push(postfix[i] - '0');
            else if (postfix[i] == '+')
            {
                tmp2 = pop();
                tmp1 = pop();
                push(tmp1 + tmp2);
            }
        }
        printf("#%d %d\n", T, pop());
    }
    return 0;
}
cs

 


'Computer Science' 카테고리의 다른 글

암호생성기  (0) 2019.01.22
계산기2  (0) 2019.01.22
magnetic  (0) 2019.01.22
GNS  (0) 2019.01.22
길찾기  (0) 2019.01.21

댓글