题目:
输入一个字符串,该字符串表示一个公式,公式里可能有整数、加减乘除符号和左右括号,计算公式的结果。如输入"48*((70-65)-43)+8*1" ,返回整数-1816.
注意:
1、假设公式不会出错,既不用考虑左右括号不配对、出现非法字符等情况。
2、计算过程或结果不用考虑溢出。
3、输入的公式中只有整数,没有小数。整数可能有负数,负数需要用括号括起来,如 “(-3)+4" 。在公式开头或括号部分的开头,负数可以没有括号,如 ”-3*4“ 和 ”(-3*4)“ 都是合法的,其他时候负数必须用括号括起来。
//具体的计算函数
int jisuan(char c, int a, int b)
{
switch (c)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a*b;
default:
return a / b;
}
}
int calculate(const string &str)
{
if (str.empty())
return 0;
//若输入函数的开头是一个没有加括号的负数,进行处理,即把“-3+4”变成“0-3+4”
string s = (str[0] == '-') ? "0" :"";
int size = str.size();
for (int i = 0; i < size; ++i)
{
//把括号里开头没有加括号的进行处理,即把“(-3+4)”变成“(0-3+4)”
if (str[i] == '(' && i <= size - 2 && str[i + 1] == '-')
{
s += "(0-";
++i;
}
else
{
s += str[i];
}
}
size = s.size();
stack<int> num,num_tmp;
stack<char> fuhao,fuhao_tmp;
int index = 0;
while (index != size)
{
//符号入栈
if (s[index] == '(' || s[index] == '+' || s[index] == '-' || s[index] == '*' || s[index] == '/')
fuhao.push(s[index++]);
//数字入栈,注意要把完整的数字入栈
else if (s[index] >= '0' && s[index] <= '9')
{
int sum = s[index] - '0';
index++;
while (index != size && s[index] >= '0' && s[index] <= '9')
{
sum = sum * 10 + s[index++] - '0';
}
num.push(sum);
}
else//右括号,此时要进行计算
{
index++;
int n1, n2 = num.top();
num.pop();
do{
char c = fuhao.top();
fuhao.pop();
n1 = num.top();
num.pop();
//由于加减号的优先级低,所以不能计算,先把内容缓存
if ( (c == '+' || c == '-') && (fuhao.top() == '*' || fuhao.top() == '/') )
{
num_tmp.push(n2);
fuhao_tmp.push(c);
n2 = n1;
}
else
{
//跟在减号后面的加减号都要变化
if (fuhao.top() == '-' && (c == '-' || c == '+'))
{
char cc = c == '+' ? '-' : '+';
n2 = jisuan(cc, n1, n2);
}
else
{
n2 = jisuan(c, n1, n2);
}
//若条件允许,需要计算缓存的内容
if (!num_tmp.empty() && (fuhao.top()=='(' || (fuhao.top() == '+' || fuhao.top() == '-')))
{
char c1 = fuhao_tmp.top();
if (fuhao.top() == '-')
{
char cc = c1 == '+' ? '-' : '+';
n2 = jisuan(cc, n2, num_tmp.top());
}
else
{
n2 = jisuan(c1, n2, num_tmp.top());
}
fuhao_tmp.pop();
num_tmp.pop();
}
}
} while (fuhao.top() != '(');
//以下两行不能忘记!
fuhao.pop();
num.push(n2);
}// 右括号end
}
//计算没有括号的部分
if (!fuhao.empty())
{
int n1, n2 = num.top();
num.pop();
do{
char c = fuhao.top();
fuhao.pop();
n1 = num.top();
num.pop();
if ((c == '+' || c == '-') && !fuhao.empty() && (fuhao.top() == '*' || fuhao.top() == '/') )
{
num_tmp.push(n2);
fuhao_tmp.push(c);
n2 = n1;
}
else// 计算
{
if (!fuhao.empty() && fuhao.top() == '-' && (c=='-' || c=='+') )
{
char cc = c == '+' ? '-' : '+';
n2 = jisuan(cc, n1, n2);
}
else
{
n2 = jisuan(c, n1, n2);
}
if (!num_tmp.empty() && (fuhao.empty() || (fuhao.top() == '+' || fuhao.top() == '-')))
{
char c1 = fuhao_tmp.top();
if (!fuhao.empty() && fuhao.top() == '-')
{
char cc = c1 == '+' ? '-' : '+';
n2 = jisuan(cc, n2, num_tmp.top());
}
else
{
n2 = jisuan(c1, n2, num_tmp.top());
}
fuhao_tmp.pop();
num_tmp.pop();
}
}//计算 end
} while (!fuhao.empty());
num.push(n2);
}
return num.top();
}原文:http://blog.csdn.net/bupt8846/article/details/45950921