LeetCode 227. Basic Calculator II

本文介绍了一个简易计算器的实现方法,该计算器能够评估简单的表达式字符串,包括加、减、乘、除四种运算,并通过堆栈来处理操作符的优先级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


This is one of the most tedious coding problem.

bool isOPTR(char s){
        if(s == '+' || s == '-' || s == '*' || s == '/' || s == '\0' || s == '#') return true;
        else return false;
    }
    
    char getPriority(char a, char b){
        int i, j;
        char priority[][5] = {
            {'>', '>', '<', '<', '>'},
            {'>', '>', '<', '<', '>'},
            {'>', '>', '>', '>', '>'},
            {'>', '>', '>', '>', '>'},
            {'<', '<', '<', '<', '='}};   // it is pretty cool here to make a table.<img alt="得意" src="http://static.blog.youkuaiyun.com/xheditor/xheditor_emot/default/proud.gif" />
        switch(a){
            case '+': i = 0; break;
            case '-': i = 1; break;
            case '*': i = 2; break;
            case '/': i = 3; break;
            case '#': i = 4; break;
        }
        switch(b){
            case '+': j = 0; break;
            case '-': j = 1; break;
            case '*': j = 2; break;
            case '/': j = 3; break;
            case '\0': j = 4; break;
        }
        return priority[i][j];
    }
    
    int Operation(int a, char theta, int b){
        if(theta == '+') return (a + b);
        else if(theta == '-') return (a - b);
        else if(theta == '*') return (a * b);
        else return (a / b);
    }
    
    int calculate(string s) {
        int len = s.size();
        if(len == 0) return 0;
        int i = 0;
        
        stack<char> OPTR;
        OPTR.push('#');
        
        stack<int> OPND;
        
        while(s[i] != '\0' || OPTR.top()!= '#'){
            if(s[i] == ' '){i++; continue;}
            else if(!isOPTR(s[i])){
                int sum = int(s[i] - '0');
                int j = i + 1;
                
                while(s[j] != '\0' && s[j] != ' ' && !isOPTR(s[j])){
                    sum = sum * 10 + int(s[j] - '0');
                    j++;
                }
                OPND.push(sum);
                i = j;
                continue;
            }else{
                switch(getPriority(OPTR.top(), s[i])){
                    case '<':
                        OPTR.push(s[i]);
                        i++;
                        break;
                    case '=':
                        OPTR.pop();   // this one is actually not very necessary.
                        i++;
                        break;
                    case '>':
                        char theta = OPTR.top();
                        OPTR.pop();
                        
                        int b = OPND.top();
                        OPND.pop();
                        
                        int a = OPND.top();
                        OPND.pop();
                        
                        OPND.push(Operation(a, theta, b));
                        break;
                } // switch
            } // else
        } // while
        return OPND.top();
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值