sicily 递归练习 1005. Arithmetic Expression Evaluation


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.

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;	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值