ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【leetcode】227. Basic Calculator II

2021-12-27 20:37:20  阅读:221  来源: 互联网

标签:运算符 存储 integers Calculator II num 227 expression Example


     Given a string s which represents an expression, evaluate this expression and return its value.  The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

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.

   这道题是将一个输入的字符串进行转换,计算字符串表示的公式。这道题只有"*"和"/",没有括号来改变计算的优先级。我一开始的计划是用两个栈分别存储数字,和运算符,运算符只存储“+”号和“-”号,乘号和除号直接将符号前后的数进行乘或者除法计算。最后根据符号栈来计算剩余数字的加减计算。

  后面发现不需要存储“+”和“-”号的符号栈,如果是“+”号,“+”后面的数字直接存储,“-”后面的数字直接乘符号加进行,这样就节省了空间。

  这道题还需要注意下代码的编写逻辑,如果当前遇到运算符,是存储上一个运算符后面的数字。

  还有个类似的题目 Basic Calculator 只有“+”,“-”,但是存在“()”影响操作顺序。

class Solution {
public:
    int calculate(string s) {
        long res=0,num=0,n=s.size();
        char op='+'; // 初始化加号
        stack<int> st;
        for(int i=0;i<n;++i){
            if(s[i]>='0'){
                num=num*10+s[i]-'0'; //计算运算数
            }
            if((s[i]<'0' && s[i]!=' ')||i==n-1){ //遇到下一个运算符
                if(op=='+') st.push(num); // 按照之前运算符来进行操作
                if(op=='-') st.push(-num);
                if(op=='*'||op=='/'){
                    int tmp=(op=='*')?st.top()*num:st.top()/num; //只有这样 栈顶的数字 和当前的num才是 *左右的带运算数
                    st.pop();
                    st.push(tmp);
                }
                op=s[i];
                num=0;
        } 
    }
     while(!st.empty()){
         res+=st.top();
         st.pop();
     }
        return res;
    }
 
};

 

  

 

标签:运算符,存储,integers,Calculator,II,num,227,expression,Example
来源: https://www.cnblogs.com/aalan/p/15737725.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有