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

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

    示例 1:

    输入:s = "1 + 1"
    输出:2
    

    示例 2:

    输入:s = " 2-1 + 2 "
    输出:3
    

    示例 3:

    输入:s = "(1+(4+5+2)-3)+(6+8)"
    输出:23
    

    提示:

    • 1 <= s.length <= 3 * 105
    • s 由数字、'+''-''('')'、和 ' ' 组成
    • s 表示一个有效的表达式
    class Solution {
    public:
        int calculate(string s) {
            int res=0;
            int sign=1;
            stack<int> nums;
            for(int i=0;i<s.size();i++){
                if(s[i]>='0'){// if s[i] is a digit
                    int cur=s[i]-'0';
                    while(i+1<s.size()&&s[i+1]>='0'){//get the whole number
                        cur=cur*10-'0'+s[i+1];//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)
                        i++;
                    }
                    res=res+sign*cur;//add the number*sign
                }
                else if(s[i]=='+'){//when '+' then sign=1
                    sign=1;
                }
                else if(s[i]=='-'){//when '-' then sign=-1
                    sign=-1;
                }
                else if(s[i]=='('){//when '(' then push res and sign and set them back to 0 and 1
                    nums.push(res);
                    res=0;
                    nums.push(sign);
                    sign=1;
                }
                else if(s[i]==')'){//when ')' then pop and add to res
                    res=res*nums.top();
                    nums.pop();
                    res+=nums.top();
                    nums.pop();
                }
            }
            return res;
        }
    };
  • 相关阅读:
    Linux学习(三十一)系统日志
    Linux学习(三十)rsync的使用
    php检测文字编码的方法
    Phpexcel使用
    高并发秒杀解决方案(转载)
    通过CSS选择器查找元素
    通过PartiaLinkText查找元素
    通过LinkText查找元素
    通过TagName查找元素
    通过ClassNmae查找元素
  • 原文地址:https://www.cnblogs.com/xxxsans/p/14515770.html
Copyright © 2011-2022 走看看