题解 | #表达式求值#

表达式求值

http://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d

#include <iostream>
#include <string>
#include <stack>
using namespace std;

int calculate(int a, int b, char sym){
    switch(sym){
        case '+':
            return a + b;
            break;
        case '-':
            return a - b;
            break;
        case '*':
            return a * b;
            break;
        case '/':
            return a / b;
            break;
        default:
            return 0;
            break;
    }
}

int process(string s){
    int flag = 0; //0无符号,1为正号,2为负号
    stack<int> numst;
    stack<char> symbolst;
    
    for(int i = 0; i < s.size(); i++){
        if(isdigit(s[i])){
            int j = i; int num = 0;
            while(i + 1 < s.size() && isdigit(s[i + 1])) i++;
            string tmp = s.substr(j, i - j + 1);
            for(int k = 0; k < tmp.size(); k++){
                num = num * 10 + (tmp[k] - '0');
            }   
            
            if(flag == 2) num = 0 - num;
            flag = 0;
            numst.push(num);
        }
        else if(s[i] == '*' || s[i] == '/' || s[i] == '('){
            symbolst.push(s[i]);
        }
        else if(s[i] == '+' || s[i] == '-'){
            if(i == 0 || s[i - 1] == '('){
                if(s[i] == '+') flag = 1;
                else flag = 2;
            }
            
            while(!flag && !symbolst.empty() && symbolst.top() != '('){
                int b = 0, a = 0;
                char sym_tmp;
                b = numst.top(); numst.pop();
                a = numst.top(); numst.pop();
                sym_tmp = symbolst.top(); symbolst.pop();
                numst.push(calculate(a, b, sym_tmp));
            }
            
            if(!flag) symbolst.push(s[i]); //
        }
        else if(s[i] == ')'){
            while(symbolst.top() != '('){
                int b = 0, a = 0;
                char sym_tmp;
                b = numst.top(); numst.pop();
                a = numst.top(); numst.pop();
                sym_tmp = symbolst.top(); symbolst.pop();
                numst.push(calculate(a, b, sym_tmp));
            }
            symbolst.pop();
        }
        else{
            cout << "error!" << endl;
        }
    }
    
    while(!symbolst.empty()){
        int b = 0, a = 0;
        char sym_tmp;
        b = numst.top(); numst.pop();
        a = numst.top(); numst.pop();
        sym_tmp = symbolst.top(); symbolst.pop();
        numst.push(calculate(a, b, sym_tmp));
    }
    
    return numst.top();
}

int main(){
    string str = "";
    while(cin >> str){
        int res = process(str);
        cout << res << endl;
    }
    
    
    return 0;
}
华为题库题解 文章被收录于专栏

牛客华为题库的题解

全部评论

相关推荐

哥_留个offer先:跟他说,你这个最好用c#,微软就用c#Java不适合这个项目
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务