題目描述
請實現如下接口
/* 功能:四則運算
* 輸入: strExpression :字符串格式的算術表達式,如 : "3+2*{1+2*[-4/(8-6)+7]}"
* 返回: 算術表達式的計算結果
*/
public static int calculate(String strExpression)
{
/* 請實現 */
return 0;
}
約束:
-
pucExpression 字符串中的有效字符包括 [‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。
-
pucExpression 算術表達式的有效性由調用者保證;
輸入描述:
輸入一個算術表達式
輸出描述:
得到計算結果
輸入例子:
3+2*{1+2*[-4/(8-6)+7]}
輸出例子:
25
思路很明確:中綴表達式轉後綴表達式,再計算後綴表達式的值即可,注意的是對於一元運算符‘-’的處理,和數字的位數要做一個記錄
寫了3個小時。。。。中間很多問題,調試了半天
代碼;
#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
int main() {
string s;
while (cin >> s) {
stack<char> opera;
vector<int> numcnt;//用來保存每個數字的位數,以保證計算後綴表達式時的正確性
string s1;//後綴表達式
//中綴表達式轉後綴表達式
for (int i = 0;i<s.size();i++) {
if (s[i] >= '0'&&s[i] <= '9') {
int tmp = 0;
while (s[i] >= '0'&&s[i] <= '9') {
tmp++;
s1 += s[i];
i++;
}
i--;
numcnt.push_back(tmp);
}
else if (s[i] == '-' || s[i] == '+') {
if (s[i] == '-' && (s[i - 1] == '(' || s[i - 1] == '[' || s[i - 1] == '{'))
s1 += '0';
while (!opera.empty()&&(opera.top() == '*' || opera.top() == '/' || opera.top() == '+' || opera.top() == '-')) {
s1 += opera.top();
opera.pop();
}
opera.push(s[i]);
}
else if (s[i] == '*' || s[i] == '/') {
while (!opera.empty()&&(opera.top() == '*' || opera.top() == '/')) {
s1 += opera.top();
opera.pop();
}
opera.push(s[i]);
}
else if (s[i] == '(' || s[i] == '[' || s[i] == '{')
opera.push(s[i]);
else if (s[i] == ')') {
while (opera.top() != '(') {
s1 += opera.top();
opera.pop();
}
opera.pop();
}
else if (s[i] == ']') {
while (opera.top() != '[') {
s1 += opera.top();
opera.pop();
}
opera.pop();
}
else if (s[i] == '}') {
while (opera.top() != '{') {
s1 += opera.top();
opera.pop();
}
opera.pop();
}
else
cout << "Invalid input!" << endl;
}
while (!opera.empty()) {
s1 += opera.top();
opera.pop();
}
//計算後綴表達式的值
stack<int> nums;
int ind = 0;
for (int i = 0;i<s1.size();i++) {
if (s1[i] >= '0'&&s1[i] <= '9') {
int total = 0;
while (numcnt[ind]--)
total = 10 * total + (s1[i++] - '0');
i--;
nums.push(total);
ind++;
}
else {
int tmp1 = nums.top();
nums.pop();
int tmp2 = nums.top();
nums.pop();
if (s1[i] == '+')
nums.push(tmp2 + tmp1);
else if (s1[i] == '-')
nums.push(tmp2 - tmp1);
else if (s1[i] == '*')
nums.push(tmp2*tmp1);
else
nums.push(tmp2 / tmp1);
}
}
cout << nums.top() << endl;
}
}