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; } };