华为2012校招成都站8:00最后一题,表达式计算源代码
主要是数字可能是多位数,需要处理!本程序没有做异常处理,要求表达式串正确!
其中有两个内部循环代码是重复的,最好写成一个函数,这里就不改了
转载 请保留链接 http://blog.csdn.net/challenge_c_plusplus/article/details/7982076
/*表达式计算-华为校招Author : Milo.WangDate : 2012/9/15*/#include <iostream>#include <cstring>using namespace std;void Expr(const char *expr, int *ret){char expr1[1024];char expr2[1024];strcpy(expr1,expr);strcpy(expr2,expr);int opds[1024];char oprs[1024];int idxd = 0, idxr = 0;int opd_idx = -1;char * p = strtok(expr1,"()*+-");while(p != NULL){opds[idxd++] = atoi(p);p = strtok(NULL,"()*+-");}int i;int digit_flag = true;for(i = 0; expr2[i] != '\0'; ++i){switch(expr2[i]){case '(':case ')':case '+':case '-':case '*':digit_flag = true;oprs[idxr++] = expr2[i];break;default:if(digit_flag){digit_flag = false;oprs[idxr++] = '#';//特殊符号,标示有一个数字}}}oprs[idxr++] = '\0';int opd_stack[1024];char opr_stack[1024];int opd_top = -1;int opr_top = -1;int opdr,opdl;for(i = 0; i < idxr; ++i){char ch;switch((ch = oprs[i])){case '*':case '(':opr_stack[++opr_top] = ch;break;case '+':case '-':while(opr_top > -1 && opr_stack[opr_top] == '*'){--opr_top;opdr = opd_stack[opd_top--];opdl = opd_stack[opd_top--];opd_stack[++opd_top] = opdl * opdr;}opr_stack[++opr_top] = ch;break;case ')':while(opr_top > -1 && opr_stack[opr_top] != '('){opdr = opd_stack[opd_top--];opdl = opd_stack[opd_top--];char c;int result;switch((c = opr_stack[opr_top--])){case '*':result = opdl * opdr;break;case '+':result = opdl + opdr;break;case '-':result = opdl - opdr;break;}opd_stack[++opd_top] = result;}if(opr_stack[opr_top] == '(')--opr_top;break;case '\0':while(opr_top > -1){opdr = opd_stack[opd_top--];opdl = opd_stack[opd_top--];char c;int result;switch((c = opr_stack[opr_top--])){case '*':result = opdl * opdr;break;case '+':result = opdl + opdr;break;case '-':result = opdl - opdr;break;}opd_stack[++opd_top] = result;}break;case '#':opd_stack[++opd_top] = opds[++opd_idx];}}*ret = opd_stack[opd_top];}int main(int argc, char *argv[]){const char *str = "5+6*(5-2)-10";int ret;Expr(str,&ret);cout << str << " = " << ret << endl;return 0;}