hiho169周 - 表达式求值

题目链接

计算表达式100*(2+12)-(20/3)*2

--------------------------------------------------------------------------------------------------------

主要思路是找最后计算的运算符

括号里面的运算符肯定不是最后算的,所以要找括号外的,如果括号外有+-号肯定要选+-,没有则找*/,再没有说明整个表达式被括起来了。

#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>

#define MAX(a,b) ((a)>=(b)?(a):(b))
#define MIN(a,b) ((a)<=(b)?(a):(b))
#define OO 0x0fffffff
using namespace std;
typedef long long LL;
const int N = 128;
char str[N];
int cal(int s,int e){
     int number=0; bool isAnum=true;
     for(int i=s;i<e;i++){
         if(str[i]<'0'||str[i]>'9') {isAnum=false;break;}
         number=number*10+str[i]-'0';
     }
     if(isAnum) return number;

     int cnt=0;
     int lv1=-1,lv2=-1;
     for(int i=s;i<e;i++){
        switch(str[i]){
           case '(':cnt++; break;
           case ')':cnt--; break;
           case '+':case '-': if(!cnt) lv1=i;break;
           case '*':case '/': if(!cnt) lv2=i;break;
        }
     }
     if(lv1<0) lv1=lv2;
     if(lv1<0) return cal(s+1,e-1);
     switch (str[lv1]){
         case '+' : return cal(s,lv1) + cal(lv1+1,e);
         case '-' : return cal(s,lv1) - cal(lv1+1,e);
         case '*' : return cal(s,lv1) * cal(lv1+1,e);
         case '/' : return cal(s,lv1) / cal(lv1+1,e);
     }
}
int main(){
    scanf("%s",str);
    printf("%d\n",cal(0,strlen(str)));
    return 0;
}

 

转载于:https://www.cnblogs.com/redips-l/p/7598774.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值