eg:
Input: "1+3*18/2+7-3*4"
Output: 23
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int vals[128];
int valTop=0;
int valBottom=0;
char ops[128];
char opTop=0;
char opBottom=0;
bool valIsEmpty()
{
return valBottom == valTop;
}
void getTopVal(int *val)
{
*val = vals[valTop-1];
}
void popVal()
{
valTop--;
}
bool opIsEmpty()
{
return opBottom == opTop;
}
void getTopOp(char *op)
{
*op = ops[opTop-1];
}
void popOp()
{
opTop--;
}
bool cal(int a,int b,int *res,char op)
{
if(op=='/' && b==0){
return false;
}
switch (op) {
case '+':
*res = a + b;
break;
case '-':
*res = a - b;
break;
case '*':
*res = a * b;
break;
case '/':
*res = a / b;
break;
default:
break;
}
return true;
}
bool Calc(const char* expression, int *res)
{
int len = strlen(expression);
int idx = 0;
// "1+3*18/2+7-3*4"
while(idx < len){
if(expression[idx] >= '0' && expression[idx] <= '9' || idx==0) {
char *p = expression+idx;
char *end;
int val = strtol(p,&end,10);
int dis = end - p;
idx+=dis;
if(opIsEmpty()) {
vals[valTop]=val;
valTop++;
continue;
} else {
char op;
getTopOp(&op);
if (op=='*' || op=='/'){
popOp();
int a;
getTopVal(&a);
popVal();
int result;
bool ret = cal(a,val,&result,op);
if(!ret){
return false;
}
vals[valTop]=result;
valTop++;
} else{
vals[valTop]=val;
valTop++;
}
}
}else {
ops[opTop]=expression[idx];
opTop++;
idx++;
}
}
while(!opIsEmpty()) {
int b;
getTopVal(&b);
popVal();
int a;
getTopVal(&a);
popVal();
char op;
getTopOp(&op);
popOp();
int result;
cal(a,b,&result,op);
vals[valTop]=result;
valTop++;
}
for(int i=0;i<valTop;i++){
printf("%d ",vals[i]);
}
printf("\n");
for(int i=0;i<opTop;i++){
printf("%c ",ops[i]);
}
printf("\n");
return true;
}
int main() {
char *str = "-1+3*18/2+7-3*4";
int res;
Calc(str,&res);
return 0;
}