-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate_expression_x_y.cpp
57 lines (55 loc) · 1.63 KB
/
evaluate_expression_x_y.cpp
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
#include <iostream>
#include <stack>
using namespace std;
int evaluate(const string& f, int &x, int &y, int &z) {
int cur_sum_y = 0;
int cur_sum_x = 0;
int cur_sum_num = 0;
int last_op = 1, bracket_op = 1;
stack<int> brackets;
for(int i = 0; i <= f.size(); ++i) {
char c = f[i];
if(isdigit(f[i])) {
int over = i + 1;
while( over< f.size() && isdigit(over))
++over;
int number = stoi(f.substr(i,over-i)) * last_op * bracket_op;
if(f[over] == 'x') {
cur_sum_x += number;
cout<<number<<endl;
i = over;
} else if(f[over] == 'y') {
cur_sum_y += number;
/* cout<<last_op<<endl;
cout<<bracket_op<<endl;
cout<<cur_sum_y<<endl;*/
i = over;
} else {
cur_sum_num += number;
i = over - 1;
}
}else if( c == 'x' ) {
cur_sum_x += last_op * bracket_op;
} else if( c == 'y' ){
cur_sum_y += last_op * bracket_op;
} else if( c == '(' ) {
brackets.push(last_op);
bracket_op *= last_op;
last_op = 1;
} else if( c == ')' ) {
bracket_op *= brackets.top();
brackets.pop();
} else if( c == '+' || c =='-') {
last_op = (c == '+')?1:-1;
} else if (c == '=') {
bracket_op = -1 ;
last_op = 1;
}
}
}
int main() {
// your code goes here
string s{"5 + 2x - ( 3y + 2x - ( 7 - 2x ) - 9 ) = 2y + 1"};
evaluate(s);
return 0;
}