Description
Arithmetic expression can be defined recursively as following:
(1) If a is a positive integer number, then a is an arithmetic expression.
(2) If a is a negative integer number, then (a) is an arithmetic expression.
(3) If e and f are arithmetic expressions, then (e+f), (e*f),(e-f),and (e/f) are all arithmetic expressions.
The expression ((6*(-7))+(-9)) is an example of arithmetic expression, and its value is -51.
Write a program that accepts an arithmetic expression represented as a string, output its value as an integer.
A string representing an arithmetic expression on one line.
The value of the arithmetic expression on one line.
((6*(-7))+((-9)/3))
-45
注意提供的是标准的运算式,每次去掉一对括号,递归要注意结构步骤的相似性;
#include <iostream> #include <string> #include <sstream> using namespace std; istringstream ss; int a,b,l; int f( string s ) { if (s[0]!='(') { if (s[0]=='-') { int sum=0; for (int i=1;i<s.size();i++) sum=sum*10+s[i]-'0'; return -sum; } else { int sum=0; for (int i=0;i<s.size();i++) sum=sum*10+s[i]-'0'; return sum; } } else { int rem=0,lo; for (int i=1;i<s.size();i++) { if(s[i]=='(') rem--; if(s[i]==')') rem++; if (rem==0&&s[i]!='('&&s[i]!=')'&&!isdigit(s[i])) { lo=i; break; } } if (s[lo]=='+') return f(s.substr(1,lo-1))+f(s.substr(lo+1,s.size()-lo-2)); if (s[lo]=='-') return f(s.substr(1,lo-1))-f(s.substr(lo+1,s.size()-lo-2)); if (s[lo]=='*') return f(s.substr(1,lo-1))*f(s.substr(lo+1,s.size()-lo-2)); if (s[lo]=='/') return f(s.substr(1,lo-1))/f(s.substr(lo+1,s.size()-lo-2)); } } int main() { string s; while(cin>>s) { int a=f(s); cout<<a<<endl; } }