问题
给一个可包含+、-、*、/运算符和()的四则运算表达式,返回该表达式值(规定所有除都会是整数结果)。
解题思路
首先明确表达式定义
接下来按照这个定义写出对应递归代码即可。
代码
#include<iostream>
#include<sstream>
#include<string>
#include<cstdio>
typedef long long LL;
using namespace std;
stringstream ss;
LL factorValue(); //计算一个因子值 (因子由 整数 或 (表达式)构成)
LL termValue(); //计算一个项的值
LL expressionValue(); //计算一个表达式值
//计算一个表达式值
LL expressionValue(){
LL result = termValue();
bool more = true;
while(more){
char c = ss.peek();
if(c == '+'){
ss.get();
result += termValue();
}
else if(c == '-'){
ss.get();
result -= termValue();
}
else
more = false;
}
return result;
}
LL termValue(){
LL result = factorValue();
bool more = true;
while(more){
char c = ss.peek();
if(c == '*' || c == '/'){
ss.get();
result = c == '*' ? result * factorValue() : result / factorValue();
}
else more = false;
}
return result;
}
LL factorValue(){
LL result = 0;
char c = ss.peek();
if(c == '('){
ss.get();
result = expressionValue();
ss.get(); //拿掉右括号
}
else{
//读取一个整数
int num;
while(ss.peek() >= '0' && ss.peek() <= '9'){
num = ss.get() - '0';
result = result * 10 + num;
}
}
return result;
}
int main(){
//io流换成string流是为了模拟题目要求直接处理给定字符串情况。
string s;
cin >> s;
ss << s;
cout << expressionValue() << endl;
return 0;
}
//(1+2)*2+45*2