您的位置:首页 > 编程语言 > Lua

sicily 递归练习 1005. Arithmetic Expression Evaluation

2016-01-15 17:48 423 查看
Description Arithmetic expression can be defined recursively as following: (1) If a is a positive integer number, thena 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.Input A string representing an arithmetic expression on one line.Output The value of the arithmetic expression on one line.Sample Input
((6*(-7))+((-9)/3))
Sample Output
-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;	}}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: