/*
问题描述:输入一个只包含个位数字的简单四则运算表达式字符串,计算该表达式的值注
1、表达式只含+,-,*,/四则运算符,不含括号
2、表达式数值只包含个位整数(0-9),且不会出现0作为除数的情况
3、要考虑加减乘除按通常四则运算规定的计算优先级
4、除法用整数除法,即仅保留除法运算结果的整数部分。比如8/3=2。输入表达式保证无0作为除数情况发生
5、输入字符串一定是符合题意合法的表达式,其中只包括数字字符和四则运算符字符,
除此之外不含其它任何字符,不会出现计算溢出情况
*/
问题描述:输入一个只包含个位数字的简单四则运算表达式字符串,计算该表达式的值注
1、表达式只含+,-,*,/四则运算符,不含括号
2、表达式数值只包含个位整数(0-9),且不会出现0作为除数的情况
3、要考虑加减乘除按通常四则运算规定的计算优先级
4、除法用整数除法,即仅保留除法运算结果的整数部分。比如8/3=2。输入表达式保证无0作为除数情况发生
5、输入字符串一定是符合题意合法的表达式,其中只包括数字字符和四则运算符字符,
除此之外不含其它任何字符,不会出现计算溢出情况
*/
int calculate(int len,char *expStr)
{
char queue[128] = {'\0'};
int head=0;
int tail=0;
char *str = expStr;
int res,opt1,opt2;
char buf,op,r[2];
#ifdef DEBUG
printf("start\n");
#endif
while(*str != '\0')
{
#ifdef DEBUG
printf("tail = %d,*str=%c\n",tail,*str);
#endif
if(*str == '*')
{
tail--;
buf = queue[tail];
opt1 = buf - '\0';
str++;
buf = *str;
opt2 = atoi(&buf);
res = opt1*opt2;
buf = '\0'+res;
queue[tail] = buf;
tail++;
str++;
#ifdef DEBUG
printf("* buf = %c\n",buf);
#endif
}else if(*str == '/'){
tail--;
buf = queue[tail];
opt1 = buf - '\0';
str++;
buf = *str;
opt2 = atoi(&buf);
res = opt1/opt2;
buf = '\0'+res;
queue[tail] = buf;
tail++;
str++;
#ifdef DEBUG
printf("/ buf = %c\n",buf);
#endif
}
else if(*str == '+'||*str == '-'){
queue[tail] = *str;
tail++;
str++;
}else{
buf = *str;
res = atoi(&buf);
buf = '\0'+res;
queue[tail] = buf;
tail++;
str++;
}
}
#ifdef DEBUG
printf("queue = %s,head = %d,tail = %d\n",queue,head,tail);
#endif
res = 0;
while(head < tail)
{
if(queue[head] == '+')
{
head++;
buf = queue[head];
opt1 = buf-'\0';
res = res+opt1;
head++;
}else if(queue[head] == '-'){
head++;
buf = queue[head];
opt1 = buf-'\0';
res = res-opt1;
head++;
}
else{
buf = queue[head];
res = buf - '\0';
head++;
}
}
return res;
}