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
說明:先將中綴表達式轉化爲後綴表達式,再由後綴表達式計算表達式的值。
代碼:
struct pri
{
char op;
int pri;
};
//設置符號的優先級,便於後續比較符號優先級
struct pri PriArray[5] = {{'=',0}, {'+',1}, {'-',1}, {'*',2}, {'/',2}};
//查找符號的優先級
int findpri(char c)
{
int i = 0;
for(i = 0; i < 5; i++)
{
if(c == PriArray[i].op)
return PriArray[i].pri;
}
return 0;
}
//比較兩個符號的優先級(符號棧棧頂符號和遍歷中綴表達式的符號)
int pricom(char top, char tmp)
{
if(findpri(top) < findpri(tmp))//棧頂符號優先級低,入棧
return 1;
else //棧頂符號優先級高,出棧
return -1;
}
//中綴表達式轉換爲後綴表達式
void transfer(char *s, char* postfix)
{
char *opStack = (char *)malloc(sizeof(char) * strlen(s)); //存放中綴表達式符號的棧
int top = -1;
top++;
char c;
int i = 0, j = 0;
opStack[top] = '=';
while(s[i] != '\0')
{
c = s[i];
if(c >= '0' && c <= '9')
{
while(s[i] >= '0' && s[i] <= '9')
{
postfix[j++] = s[i++];
}
postfix[j++] = '#';
}
else if(c == ' ')
{
i++;
}
else
{
switch(pricom(opStack[top], c)){
case 1:
top++;
opStack[top] = c;
i++;
break;
case -1:
while(pricom(opStack[top], c) == -1)
{
postfix[j++] = opStack[top];
top--;
}
top++;
opStack[top] = c;
i++;
break;
}
}
}
while(top > 0) //將符號棧剩餘符號全部出棧
{
postfix[j++] = opStack[top];
top--;
}
postfix[j] = '\0';
free(opStack);
}
//計算表達式的值
int calculate(char* s) {
int *num = (int *)malloc(sizeof(int) * strlen(s)); //存儲後綴表達式的數字
int a = 0, b = 0;
char *postfix = (char *)malloc(sizeof(char) * 2 * strlen(s)); //存儲後綴表達式
transfer(s, postfix);
//printf("%s\n",postfix);
int top = -1, i = 0;
int tmp;
//由後綴表達式計算表達式的值
while(postfix[i] != '\0')
{
switch(postfix[i]){
case '+':
a = num[top--];
b = num[top--];
num[++top] = a + b;
i++;
break;
case '-':
a = num[top--];
b = num[top--];
num[++top] = b - a;
i++;
break;
case '*':
a = num[top--];
b = num[top--];
num[++top] = a * b;
i++;
break;
case '/':
a = num[top--];
b = num[top--];
num[++top] = b / a;
i++;
break;
default:
tmp = 0;
while(postfix[i] >= '0' && postfix[i] <= '9')
{
tmp = 10 * tmp + postfix[i] - '0';
i++;
}
num[++top] = tmp;
if(postfix[i] == '#')
i++;
break;
}
}
i = num[top];
free(num);
return i;
}