zoukankan      html  css  js  c++  java
  • 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
    ",cal(0,strlen(str)));
        return 0;
    }
  • 相关阅读:
    控制element表格禁用选择
    深度拷贝
    VScode修复eslint报错,保存的时候自动格式修正
    关于route监听
    PAT 1030 完美数列
    PAT1029 旧键盘(C完全正确)
    PAT 1028 人口普查
    PAT 1016
    PAT:1013
    PAT :1012 数字分类
  • 原文地址:https://www.cnblogs.com/redips-l/p/7598774.html
Copyright © 2011-2022 走看看