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; }}
相关文章推荐
- lua和c的亲密接触
- lua BaseClass
- lua 怎么写两个字符串相加
- (java)Evaluate Reverse Polish Notation
- LUA解析json小demo
- LUA解析json小demo
- windows下编译LUA-cjson
- windows下编译LUA-cjson
- lua c closure的使用
- lua 绑定c++
- liunx 下 C/C++调用luajit
- 用lua写Android界面学习笔记
- [转载]轻量级Lua IDE ZeroBrane Studio 的使用技巧和汉化
- 从零开始——Windows环境lua编程
- leetcode--Evaluate Reverse Polish Notation
- Lua 表达式
- Lua中and、or的一些特殊用法
- Lua 类型和值
- 【sublime】编译lua
- wax lua 简介