闲着没事写了一个计算器回忆一下,支持加减乘除,括号,10以上的运算和负数。
不过没做错误判定,你的式子要是对的才行。。。
-19+(-3-(-11))*13+4/2
我的例子
因为最近用STL比较多,为了写起来方便,所以多了很多类型转换的地方,会影响一些效率,但是这个还是以实现功能为主吧。
class Solution {
public:
int calculate(string str){
vector<string> suffixVec;
stack<char> charStack;
for (int i = 0; i<str.size(); i++) {
if (str[i] <= '9' && str[i] >='0') {
string tmpStr = "";
tmpStr += str[i];
while(i+1<str.size()&&str[i+1]<='9'&&str[i+1]>='0'){
tmpStr += str[++i];
}
suffixVec.push_back(tmpStr);
}else if (str[i] == '/' || str[i] == '*' || str[i] == '('){
charStack.push(str[i]);
}else if (str[i] == '+' || str[i] == '-'){
if(str[i] == '-' && ( i == 0 || str[i - 1] == '(')){
string tmpStr = "";
tmpStr += str[i];
while(i+1<str.size()&&str[i+1]<='9'&&str[i+1]>='0'){
tmpStr += str[++i];
}
suffixVec.push_back(tmpStr);
continue;
}
while ( !charStack.empty() &&(charStack.top() == '*' ||
charStack.top() == '/' ||
charStack.top() == '+' ||
charStack.top() == '-')) {
string tmpStr = "";
tmpStr += charStack.top();
suffixVec.push_back(tmpStr);
charStack.pop();
}
charStack.push(str[i]);
}else if (str[i] == ')'){
while (charStack.top() != '(') {
string tmpStr = "";
tmpStr += charStack.top();
suffixVec.push_back(tmpStr);
charStack.pop();
}
charStack.pop();
}
}
while (!charStack.empty()) {
string tmpStr = "";
tmpStr += charStack.top();
suffixVec.push_back(tmpStr);
charStack.pop();
}
stack<int> intStack;
int tmpResult = 0;
for (int i = 0; i<suffixVec.size(); i++) {
string ss = suffixVec[i];
if ((ss[0] <= '9' && ss[0] >= '0' )||(ss[0] == '-' && ss.size() > 1)) {
intStack.push(atoi(ss.c_str()));
}else{
int a = intStack.top();
intStack.pop();
int b = intStack.top();
intStack.pop();
if (ss[0] == '+') {
tmpResult = b + a;
}else if (ss[0] == '-'){
tmpResult = b - a;
}else if (ss[0] == '/'){
tmpResult = b / a;
}else if (ss[0] == '*'){
tmpResult = b * a;
}
intStack.push(tmpResult);
}
}
return tmpResult;
}
};