zoukankan      html  css  js  c++  java
  • 227. 基本计算器 II

    给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

    整数除法仅保留整数部分。

    示例 1:

    输入:s = "3+2*2"
    输出:7
    

    示例 2:

    输入:s = " 3/2 "
    输出:1
    

    示例 3:

    输入:s = " 3+5 / 2 "
    输出:5
    

    提示:

    • 1 <= s.length <= 3 * 105
    • s 由整数和算符 ('+', '-', '*', '/') 组成,中间由一些空格隔开
    • s 表示一个 有效表达式
    • 表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1] 内
    • 题目数据保证答案是一个 32-bit 整数
    class Solution {
    public:
        int calculate(string s) {
            int res=0,d=0;
            char sign='+';
            stack<int> nums;
            for(int i=0;i<s.size();++i){
                if(s[i]>='0'){// if s[i] is a digit
                    d=d*10-'0'+s[i];////use -'0'+s[i+1] instead of +s[i+1]-'0' in case of 
                    //Line 11: Char 31: runtime error: signed integer overflow: 2147483640 + 55 cannot be represented in type 'int' (solution.cpp)
                }
                if((s[i]<'0'&&s[i]!=' ')||i==s.size()-1){
                    if(sign=='+'){//when '+' push d
                        nums.push(d);
                    }else if(sign=='-'){//when '-' push -d
                        nums.push(-d);
                    }else if(sign=='*'||sign=='/'){
                        //when '*' pop and push nums.top()*d
                        //when '/' pop push nums.top()/d
                        int tmp=sign=='*'?nums.top()*d:nums.top()/d;
                        nums.pop();
                        nums.push(tmp);
                    }
                    sign=s[i];
                    d=0;//set d back to 0
                }
            }
            while(!nums.empty()){//add all the numbers
                res+=nums.top();
                nums.pop();
            }
            return res;
        }
    };
  • 相关阅读:
    Mybatis-Plus select不列出全部字段
    git合并之 merge和rebase
    git
    springboot缓存开发
    关于Maven打包
    邮件发送模型及其Python应用实例
    Python 日志模块的定制
    python 解析 XML文件
    有限状态机FSM详解及其实现
    动态规划
  • 原文地址:https://www.cnblogs.com/xxxsans/p/14515892.html
Copyright © 2011-2022 走看看