- 实现方法:双栈结构
- 可计算多位的整数
- 关注到了遇见减号时造成的运算符的更改
#include#include #include #include #include using namespace std; class Main{ public: //主函数 static int process(string s){ if (s.size() == 0){ return 0; } stack numStack;//存放数字 stack operStack;//存放运算符 for (int i = 0; i < s.size(); ++i) { char a=s[i]; if (isOper(a)){//如果是运算符 //运算符栈空或者为 ( 就直接如栈 if (operStack.empty()||a=='('){ operStack.push(a); continue; } //若为 ) ,那么就一直进行运算直到遇见第一个 ( if (a==')'){ while (operStack.top()!='('){ int num1=numStack.top(); numStack.pop(); int num2=numStack.top(); numStack.pop(); char aa=operStack.top(); operStack.pop(); int res= jisuan(num1,num2,aa); numStack.push(res); } operStack.pop(); continue; } //若为一般的运算符,优先级小于栈顶运算符,那么要先计算栈顶的数据,并将结果入数栈 if (priority(a)< priority(operStack.top())){ int num1=numStack.top(); numStack.pop(); int num2=numStack.top(); numStack.pop(); char op=operStack.top(); int res=jisuan(num1,num2,op); operStack.pop(); numStack.push(res); } operStack.push(a); } else{ //若为数字,我们要判断该数字是几位数,几位数结束标志为整个字符串结束或者遇见下一个运算符 string ss= to_string(a-'0'); while (true){ if(i+1==s.size()||isOper(s.substr(i+1,i+2)[0])){ break; } else { ss+=s.substr(i+1,i+2); i++; } } //将string转化成int numStack.push(atoi(ss.c_str())); } } while (true){ if (operStack.empty()){ return numStack.top(); } int num1=numStack.top(); numStack.pop(); int num2=numStack.top(); numStack.pop(); char op= operStack.top(); operStack.pop(); if(operStack.empty()||operStack.top()=='+'){ numStack.push(jisuan(num2, num1,op)); }else { numStack.push(jisuan(num2, num1,opReserve(op))); } } } private: //有时候前面遇见 - 会出现错误,所以要判断在运算符前一个字符是否为 - static char opReserve(char op) { if (op == '+') return '-'; else return '+'; } //判断是否为运算符 static bool isOper(char ss){ if (ss=='+'||ss=='-'||ss=='*'||ss=='/'||ss=='('||ss==')') { return true; } else{ return false; } } //根据数字和运算符计算结果 static int jisuan(int a,int b,char c){ switch (c) { case '+': return a+b; case '-':return a-b; case '*':return a*b; case '/':return a/b; } return -1; } //判断运算符优先级 static int priority(char oper){ if (oper=='+'||oper=='-'){ return 0; } else if (oper=='*'||oper=='/'){ return 1; } else{ return -1; } } }; int main(){ int re=Main::process("12+22-(34*3)-22"); cout< 欢迎分享,转载请注明来源:内存溢出
评论列表(0条)