• 227. Basic Calculator II


    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.

    ==================

    基本的+,-,*,/计算,利用栈

    ====

    思路:

    申请两个栈,一个符号栈op,一个数字栈num,

    代码:

    class Solution {
    public:
        int calculate(string s) {
            stack<char> op;
            stack<int> num;
            const int n = s.size();
            char ch;
            int tmp = 0;
            int a = 0;
            for(int i = 0;i<n;i++){
                ch = s[i];
                if(ch==' ') continue;
                else if(ch=='*' || ch=='/' || ch=='+' || ch=='-'){
                    op.push(ch);
                }else if(isdigit(ch)){
                    tmp = tmp*10+ch-'0';
                    while(i<n && isdigit(ch=s[++i])){
                        tmp = tmp*10+ch-'0';
                    }
                    if(!op.empty()){
                        char curr_op = op.top();
                        if(curr_op == '*'){
                            int a = num.top();num.pop();op.pop();
                            num.push(a*tmp);
                        }else if(curr_op == '/'){
                            a = num.top();num.pop();op.pop();
                            num.push(a/tmp);
                        }else{
                            if(curr_op == '-') tmp *=-1;
                            num.push(tmp);
                        }
                    }else{
                        num.push(tmp);
                    }
                    tmp = 0;
                    if(i==n) break;
                    i--;
                }
            }
    
            while(!op.empty()){
                int a = num.top();num.pop();
                int b = num.top();num.pop();
                //char ch = op.top();
                op.pop();
                num.push(a+b);
            }///while
            int re = num.top();num.pop();
            return re;
        }
    };
  • 相关阅读:
    navcat15 安装+激活
    页面调用百度地图但是使用了https证书之后不显示
    net core webapi 数据库连接
    asp.net core webAPI跨域问题
    本机端口(出入站)配置
    Vue页面跳转路由
    net core --- Swagger搭建(net core 3.1 版本)
    sqlserver数据库中生成随机数
    随机生成登录验证码(4位)
    定时器
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5608128.html
Copyright © 2020-2023  润新知