-
Notifications
You must be signed in to change notification settings - Fork 0
/
150.evaluate-reverse-polish-notation.c
93 lines (85 loc) · 1.8 KB
/
150.evaluate-reverse-polish-notation.c
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* @lc app=leetcode.cn id=150 lang=c
*
* [150] Evaluate Reverse Polish Notation
*/
// @lc code=start
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef enum operator
{
ADD,
SUBTRACT,
MULTIPLY,
DIVIDE,
NUMBER
} operator;
enum operator convert(char *token)
{
int len = strlen(token);
if (len == 1)
{
switch (token[0])
{
case '+':
return ADD;
case '-':
return SUBTRACT;
case '*':
return MULTIPLY;
case '/':
return DIVIDE;
default:
break;
}
}
return NUMBER;
}
int evalRPN(char **tokens, int tokensSize)
{
if (tokensSize == 1)
{
return atoi(tokens[0]);
}
int *operands = (int *)malloc(sizeof(int) * tokensSize), op_size = 0;
operands[op_size++] = atoi(tokens[0]);
int idx = 1;
enum operator op;
while (idx < tokensSize)
{
switch (op = convert(tokens[idx]))
{
case ADD:
operands[op_size - 2] += operands[op_size - 1];
op_size--;
break;
case SUBTRACT:
operands[op_size - 2] -= operands[op_size - 1];
op_size--;
break;
case MULTIPLY:
operands[op_size - 2] *= operands[op_size - 1];
op_size--;
break;
case DIVIDE:
operands[op_size - 2] /= operands[op_size - 1];
op_size--;
break;
case NUMBER:
operands[op_size++] = atoi(tokens[idx]);
break;
default:
break;
}
idx++;
}
return operands[0];
}
// @lc code=end
int main(int argc, char const *argv[])
{
char *tokens[7] = {"4", "-2", "/", "2", "-3", "-", "-"};
evalRPN(tokens, 7);
return 0;
}