NowCoder HJ50 四则运算
前言
华为机试刷题
题目: HJ50 四则运算
编程语言: C++
解题状态: 看着简单,但是搞不出来
思路
括号的本质上是使用递归来解决问题。
代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int compute(string& s, int left, int right) {
char op = '+';
int num = 0;
vector<int> st;
for (int i = left; i <= right; i++) {
if (isdigit(s[i])) {
num = num * 10 + s[i] - '0';
}
if (s[i] == '{' || s[i] == '[' || s[i] == '(') {
int layer = 0;
int j = i;
while (j <= right) {
if (s[j] == '{' || s[j] == '[' || s[j] == '(') {
layer++;
} else if (s[j] == '}' || s[j] == ']' || s[j] == ')') {
layer--;
if (layer == 0) {
break;
}
}
j++;
}
num = compute(s, i + 1, j - 1);
i = j + 1;
}
if (!isdigit(s[i]) || i == right) {
switch (op) {
case '+': st.push_back(num); break;
case '-': st.push_back(-num); break;
case '*': st.back() *= num; break;
case '/': st.back() /= num; break;
}
op = s[i];
num = 0;
}
}
int res = 0;
for (int x : st) {
res += x;
}
return res;
}
int main() {
string str;
while (cin >> str) { // 注意 while 处理多个 case
cout << compute(str, 0, str.size()) << endl;;
}
return 0;
}