1 #include<iostream> 2 #include<string> 3 #include<vector> 4 #include<algorithm> 5 #include<stack> 6 #include<map> 7 #include<sstream> 8 using namespace std; 9 10 int calculator(string s) 11 { 12 s = "("+s+")"; 13 size_t len = s.size(); 14 stack<int> num; 15 stack<char> oper; 16 map<string, bool> priority; //false时应该对放入栈顶的操作符进行运算,true时将新的操作符入栈 17 priority["++"]=false; 18 priority["+-"]=false; 19 priority["+*"]=true; 20 priority["+/"]=true; 21 priority["+("]=true; 22 priority["+)"]=false; 23 24 priority["-+"]=false; 25 priority["--"]=false; 26 priority["-*"]=true; 27 priority["-/"]=true; 28 priority["-("]=true; 29 priority["-)"]=false; 30 31 priority["*+"]=false; 32 priority["*-"]=false; 33 priority["**"]=false; 34 priority["*/"]=false; 35 priority["*("]=true; 36 priority["*)"]=false; 37 38 priority["/+"]=false; 39 priority["/-"]=false; 40 priority["/*"]=false; 41 priority["//"]=false; 42 priority["/("]=true; 43 priority["/)"]=false; 44 45 priority["(+"]=true; 46 priority["(-"]=true; 47 priority["(*"]=true; 48 priority["(/"]=true; 49 priority["(("]=true; 50 priority["()"]=false; 51 52 //int flag=1; //表示可以构造操作数 53 string sp; //从s中提取操作数到sp中 54 for(size_t i=0; i<len; i++) 55 { 56 if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/' || s[i]=='(' || s[i]==')') 57 { 58 if(!sp.empty()) 59 { 60 int temp; 61 istringstream is(sp); 62 is>>temp; 63 num.push(temp); 64 sp.clear(); 65 } 66 67 char c = s[i]; 68 if(oper.empty()) 69 oper.push(c); 70 else 71 { 72 char ct = oper.top(); 73 string str; 74 str.push_back(ct); 75 str.push_back(c); 76 if(true==priority[str]) //新的操作符入栈 77 oper.push(c); 78 else //对栈顶操作符进行计算 79 { 80 int a,b; 81 if(ct!='(') 82 { 83 b = num.top(); 84 num.pop(); 85 a = num.top(); 86 num.pop(); 87 } 88 int res; 89 switch(ct) 90 { 91 case '+': 92 res = a+b; 93 num.push(res); 94 break; 95 case '-': 96 res = a-b; 97 num.push(res); 98 break; 99 case '*': 100 res = a*b; 101 num.push(res); 102 break; 103 case '/': 104 res = a/b; 105 num.push(res); 106 break; 107 case '(': 108 if(c==')') 109 { 110 i++; 111 } 112 } 113 oper.pop(); 114 i--; 115 } 116 } 117 } 118 else 119 sp.push_back(s[i]); 120 } 121 122 return num.top(); 123 } 124 125 int main() 126 { 127 string s="(5+21*(5-(15-10)*3)/5+5)"; 128 int ans; 129 ans = calculator(s); 130 cout<<ans<<endl; 131 132 return 0; 133 }
需要说明的是这里的a/b实现的是整数相除,比如说3/2得到的是1而不是1.5