zoukankan      html  css  js  c++  java
  • 227. Basic Calculator II(重点记录上一个符号,每次判断上一个符号)

    Given a string s which represents an expression, evaluate this expression and return its value

    The integer division should truncate toward zero.

    Example 1:

    Input: s = "3+2*2"
    Output: 7
    

    Example 2:

    Input: s = " 3/2 "
    Output: 1
    

    Example 3:

    Input: s = " 3+5 / 2 "
    Output: 5
    

    Constraints:

    • 1 <= s.length <= 3 * 105
    • s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
    • s represents a valid expression.
    • All the integers in the expression are non-negative integers in the range [0, 231 - 1].
    • The answer is guaranteed to fit in a 32-bit integer.
     
    class Solution {
    public:
        //带括号的话,用递归,更难一些(找到对应层级的括号并同时删除)
        int calculate(string s) {
            //利用栈: 3+5/2*3转化为 +3 +5 /2 *3
            stack<int> nums;
            int n = s.size();
            int num = 0,res =0,pre=0;
            char sign = '+';
            for(int i=0;i<n;i++){
                //if(isspace(s[i])) continue; 忽略不用管空格
                if(isdigit(s[i])){
                    num = num*10+(s[i]-'0');
                }
                if(!isspace(s[i]) && !isdigit(s[i]) || i == n-1){
                    switch (sign){
                    case '+':
                        nums.push(num);
                        break;
                    case '-':
                        nums.push(-num);
                        break;
                    case '*':
                        pre=nums.top();
                        nums.pop();
                        nums.push(pre*num);
                        break;
                    case '/':
                        pre=nums.top();
                        nums.pop();
                        nums.push(pre/num);
                        break;
                    }
                    sign = s[i];
                    num = 0;
                }
                
            }
            while(!nums.empty()){
                res += nums.top();
                nums.pop();
            }
            return res;
        }
    };
  • 相关阅读:
    Delphi 拖动
    Unknown picture file extension
    鼠标指针形状
    C_FD_PhysRDBMSKinds
    delphichromiumembedded
    delphi使用 DockForm DesignEditors F2613 Unit 'DockForm' not found
    TBitConverter
    sql 存储过程返回值 变量名
    XE7 数据库独立运行需要的文件
    C++Builder 内存泄露检测
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/14076139.html
Copyright © 2011-2022 走看看