224. Basic Calculator
- Total Accepted: 32728
- Total Submissions: 139195
- Difficulty: Hard
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open (
and closing parentheses )
, the plus +
or minus sign -
, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval
built-in library function.
思路:见代码。
代码:
num表示当前项的数值,res表示之前所有项的和,sign表示的前一项的符号。
1 class Solution { 2 public: 3 int calculate(string s) { 4 stack<int> nums; 5 int sign=1,res=0,num=0; 6 for(int i=0;i<s.size();i++){ 7 if(isdigit(s[i])){ 8 num*=10; 9 num+=s[i]-'0'; 10 } 11 else{ 12 res+=num*sign; 13 num=0; 14 if(s[i]=='+'){ 15 sign=1; 16 } 17 if(s[i]=='-'){ 18 sign=-1; 19 } 20 if(s[i]=='('){ 21 nums.push(res); 22 nums.push(sign); 23 res=0; 24 sign=1; 25 } 26 if(s[i]==')'){ 27 res*=nums.top(); 28 nums.pop(); 29 res+=nums.top(); 30 nums.pop(); 31 } 32 } 33 } 34 return res+=sign*num; 35 } 36 };