Basic Calculator II

来源:互联网 发布:java测试工程师做什么 编辑:程序博客网 时间:2024/06/06 14:09

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:
“3+2*2” = 7
” 3/2 ” = 1
” 3+5 / 2 ” = 5
Note: Do not use the eval built-in library function.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.
思路:简单的表达式求值,一个stack存储操作数,一个栈存储运算符;顺序遍历字符串,碰到操作数以及运算符,分别添加到对应的栈中,添加运算符时需要注意,如果待添加的运算符的优先级不高于栈顶的运算符,则取出(需要出栈)数据栈顶的两个操作数以及运算符栈的栈顶操作符(需要出栈)进行运算,并将结果压入操作数栈中,直到运算符栈为空。当遍历结束时,如果运算符栈非空,则仍然需要取出(需要出栈)数据栈顶的两个操作数以及运算符栈的栈顶操作符(需要出栈)进行运算,并将结果压入操作数栈中,直到运算符栈为空。(说的有点累赘)
代码如下:

class Solution {public:    bool isoperator(char ch){        if(ch == '+' || ch == '-' || ch == '*' || ch == '/')            return true;        return false;    }    int isPrior(char a, char b){        if(a == '*' || a == '/'){            if(b == '*' || b == '/')                return 0;//优先级相同            else                return 1;//a的优先级高于b        }        else{            if(b == '*' || b == '/')                return -1;//b的优先级高于a            return 0;//优先级相同        }    }    int value(int a, char o ,int b){        switch(o){            case '+':                return a + b;            case '-':                return a - b;            case '*':                return a * b;            case '/':                return a / b;        }    }    int calculate(string s){        stack<int> data, oper;        int len = s.length();        for(int i = 0; i < len; ++i){            char c = s[i];            if(isblank(c))                continue;            else if(isoperator(c)){                if(oper.empty())                    oper.push(c);                else{                    while(!oper.empty() && isPrior(c, oper.top()) < 1){//c的优先级不高与当前栈顶操作符优先级                        int a  = data.top();                        data.pop();                        int b = data.top();                        data.pop();                        int v  = value(b, oper.top(), a);                        data.push(v);                        oper.pop();                    }                      oper.push(c);                }            }            else{                string str = "";                while(i < len && isdigit(s[i])){                    str += s[i];                    i++;                }                i--;                data.push(atoi(str.c_str()));            }        }        while(!oper.empty()){            int a  = data.top();            data.pop();            int b = data.top();            data.pop();            int v  = value(b, oper.top(), a);            data.push(v);            oper.pop();        }        return data.top();    }};
0 0
原创粉丝点击