表达式求值

表达式计算4

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <queue>
#include <string.h>
#include <cmath>
#include <bitset>
#define ll long long
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
using namespace std;

//void print(char a[])
//{
//    printf("%d %c\n",strlen(a),a[2]);
//} 

char s[35];
int qpow(int a,int b)
{
	int res = 1;
	while(b){
		if(b&1) res *= a;
		a *= a;
		b >>= 1;
	}
	return res;
}

int change(int l,int r)
{
	int ans = 0;
    for(int i = l; i <= r; i++){
    	ans = ans * 10 + s[i] - '0';
	}
	return ans;	
}

int cal(int l,int r)
{
	int p1 = -1,p2 = -1,p3 = -1,cnt = 0;
	for(int i = l; i <= r; i++){
		if(s[i] == '(') cnt++;
		if(s[i] == ')') cnt--;
		if(cnt == 0){
			if(s[i] == '+' || s[i] == '-') p1 = i;
			if(s[i] == '*' || s[i] == '/') p2 = i;
			if(s[i] == '^') p3 = i;
		}
	}
	//左括号多余( ( ( ) )
	if(cnt > 0 && s[l] == '(') return cal(l+1,r);
	//右括号多余( ( ) ) ) 
	if(cnt < 0 && s[r] == ')') return cal(l,r-1);
	//去掉两端括号 ( ...... ) 
	if(s[l] == '(' && s[r] == ')' && p1 == -1 && p2 == -1 && p3 == -1)
	    return cal(l+1,r-1);
	if(p1 != -1){
		if(s[p1] == '+') return cal(l,p1-1) + cal(p1+1,r);
		else return cal(l,p1-1) - cal(p1+1,r);
	}
	if(p2 != -1){
		if(s[p2] == '*') return cal(l,p2-1) * cal(p2+1,r);
		else return cal(l,p2-1) / cal(p2+1,r);
	}
	if(p3 != -1){
		 return qpow(cal(l,p3-1),cal(p3+1,r));
	}
	return change(l,r);
}

int main()
{
	scanf("%s",s);
	int len = strlen(s);
	printf("%d\n",cal(0,len - 1));
	return 0;
}

表达式求值:栈

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <queue>
#include <string.h>
#include <cmath>
#include <bitset>
#define ll long long
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
using namespace std;

//void print(char a[])
//{
//    printf("%d %c\n",strlen(a),a[2]);
//} 

string s;
int main()
{
	cin >> s;
	int len = s.length();
	ll sum = 0,res = 0;
	stack<ll>s1;
	stack<string>s2;
	s += '#';
	for(int i = 0; i <= len; i++){
		if(s[i] >= '0' && s[i] <= '9') res = res * 10 + s[i] - '0';
		else{
			string k;
			res %= 10000;
			s1.push(res);
			res = 0;
			if(!s2.empty() && s2.top() == "*") {
				s2.pop();
				int temp = s1.top();
				s1.pop();
				temp *= s1.top();
				s1.pop();
				temp %= 10000; 
				//cout << temp << endl;
				s1.push(temp);
			}
			k += s[i];
			s2.push(k);
		} 
	}
	while(!s1.empty()){
		sum = (sum + s1.top()) % 10000;
		s1.pop();
	}
	cout << sum;
	return 0;
}


全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务