算法訓練 表達式計算

問題描述

輸入一個只包含加減乖除和括號的合法表達式,求表達式的值。其中除表示整除。

輸入格式

輸入一行,包含一個表達式。

輸出格式

輸出這個表達式的值。

樣例輸入

1-2+3*(4-5)

樣例輸出

-4

數據規(guī)模和約定

表達式長度不超過100,表達式運算合法且運算過程都在int內進行。

利用棧和后綴表達式來做

#include <bits/stdc++.h>
using namespace std;

char *infix2postfix(char *exp) {
    char *postExp = new char[200];
    int cnt = 0;
    stack<char> st;
    for(int i = 0; i < strlen(exp); i++) {
        if(isdigit(exp[i])) {
            postExp[cnt++] = exp[i];
        } else {
            if(isdigit(postExp[cnt-1])) {
                postExp[cnt++] = '#';
            }
            if(exp[i] == '+' || exp[i] == '-') {
                if(!st.empty()) {
                    while(!st.empty() && st.top() != '(') {
                        postExp[cnt++] = st.top();
                        st.pop();
                    }
                }
                st.push(exp[i]);
            } else if(exp[i] == '*' || exp[i] == '/' || exp[i] == '(') {
                st.push(exp[i]);
            } else if(exp[i] == ')') {
                while(st.top() != '(') {
                    postExp[cnt++] = st.top();
                    st.pop();
                }
                st.pop();
            }
        }
    } 
    while(!st.empty()) {
        postExp[cnt++] = st.top();
        st.pop();
    }
    
    postExp[cnt] = 0;
    return postExp;
} 

int calculate(char *post) {
    int ans = 0;
    int a, b;
    stack<int> st;
    for (int i = 0; i < strlen(post); i++) {
        a = b = 0;
        if(isdigit(post[i])) {
            while(isdigit(post[i])) {
                b = post[i] - '0';
                a = a * 10 + b;
                i++;
            }
            if(post[i] != '#')
                i--;
            //cout << a << endl; 
            st.push(a);
        } else {
            a = st.top();
            st.pop();
            b = st.top();
            st.pop();
            switch(post[i]) {
                case '+':
                    ans = a + b;    
                    break;
                case '-':
                    ans = b - a;
                    break;
                case '*':
                    ans = a * b;
                    break;
                case '/':
                    ans = b / a;
                    break;
            }
            //cout << ans << endl;
            st.push(ans);
        }
    }
    
    return ans;
}

int main() {
    char exp[101];
    char *postExp = new char[200];
    scanf("%s", exp);
    postExp = infix2postfix(exp);
    //printf("%s\n", postExp);
    printf("%d\n", calculate(postExp));
    
    return 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容