Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers,
+
, -
, *
, /
operators and empty spaces
. The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
Note: Do not use the eval
built-in library function.
This is one of the most tedious coding problem.
bool isOPTR(char s){
if(s == '+' || s == '-' || s == '*' || s == '/' || s == '\0' || s == '#') return true;
else return false;
}
char getPriority(char a, char b){
int i, j;
char priority[][5] = {
{'>', '>', '<', '<', '>'},
{'>', '>', '<', '<', '>'},
{'>', '>', '>', '>', '>'},
{'>', '>', '>', '>', '>'},
{'<', '<', '<', '<', '='}}; // it is pretty cool here to make a table.<img alt="得意" src="http://static.blog.youkuaiyun.com/xheditor/xheditor_emot/default/proud.gif" />
switch(a){
case '+': i = 0; break;
case '-': i = 1; break;
case '*': i = 2; break;
case '/': i = 3; break;
case '#': i = 4; break;
}
switch(b){
case '+': j = 0; break;
case '-': j = 1; break;
case '*': j = 2; break;
case '/': j = 3; break;
case '\0': j = 4; break;
}
return priority[i][j];
}
int Operation(int a, char theta, int b){
if(theta == '+') return (a + b);
else if(theta == '-') return (a - b);
else if(theta == '*') return (a * b);
else return (a / b);
}
int calculate(string s) {
int len = s.size();
if(len == 0) return 0;
int i = 0;
stack<char> OPTR;
OPTR.push('#');
stack<int> OPND;
while(s[i] != '\0' || OPTR.top()!= '#'){
if(s[i] == ' '){i++; continue;}
else if(!isOPTR(s[i])){
int sum = int(s[i] - '0');
int j = i + 1;
while(s[j] != '\0' && s[j] != ' ' && !isOPTR(s[j])){
sum = sum * 10 + int(s[j] - '0');
j++;
}
OPND.push(sum);
i = j;
continue;
}else{
switch(getPriority(OPTR.top(), s[i])){
case '<':
OPTR.push(s[i]);
i++;
break;
case '=':
OPTR.pop(); // this one is actually not very necessary.
i++;
break;
case '>':
char theta = OPTR.top();
OPTR.pop();
int b = OPND.top();
OPND.pop();
int a = OPND.top();
OPND.pop();
OPND.push(Operation(a, theta, b));
break;
} // switch
} // else
} // while
return OPND.top();
}