zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    Spring_依赖注入DI
    Spring_懒加载与非懒加载
    Spring_提示模板配置/搭建spring框架/单例与多例/初始化方法和销毁方法
    Spring
    Mybatis_二级缓存
    Mybatis_一级缓存
    Mybatis_一对多延迟加载
    Mybatis_一对一查询
    MapReduce的核心资料索引 [转]
    Hadoop家族的各个成员
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5608128.html
Copyright © 2011-2022 走看看