class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return int整型 */ int calculate(string s) { // write code here s += '&'; stack<int> number1; stack<char> operation; int i = 0; int flag = 0; int tmp = 0; while (i < s.length()) { if (s[i] <= '9' && s[i] >= '0') { tmp = tmp * 10 + s[i] - '0'; } else { number1.push(tmp); tmp = 0; if (flag == 1) { int num1 = number1.top(); number1.pop(); int num2 = number1.top(); number1.pop(); char opra = operation.top(); operation.pop(); if (opra == '*') number1.push(num1 * num2); else if (opra == '/') number1.push(num2 / num1); flag = 0; } if (s[i] == '+' || s[i] == '-' || s[i] == '&') { while (!operation.empty()) { int num1 = number1.top(); number1.pop(); int num2 = number1.top(); number1.pop(); char opera = operation.top(); operation.pop(); if (opera == '+') number1.push(num2 + num1); else if (opera == '-') number1.push(num2 - num1); else if (opera == '*') number1.push(num2 * num1); else if (opera == '/') number1.push(num2 / num1); } } else flag = 1; operation.push(s[i]); } i++; } return number1.top(); } };