Basic Calculator
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.
- 如果当前字符c是数字字符,数字可能不止一位,所以需要继续遍历下一个字符,若仍然是数字字符,将其与前面的连续数字字符组成一个数num,直到遇到下一个非数字字符;
- 如果当前的字符c是'+',那么就将前面的num加到result中,并且设置符号标记sign=1为正;
- 如果当前字符c是'-',那么就用result - num,并且设置符号标记sign=-1为负;
- 如果当前字符c是'(',那么先保存当前的result和符号sign到栈中,再继续计算括号里面的表达式;
- 如果当前字符c是')',那么计算完毕当前括号的result后,依次弹出栈顶的sign和result,然后将括号中的result和栈顶弹出的result相加(或相减,由sign决定);
- 继续以上步骤,直到遍历到字符串的最后一个字符
Runtime: 16ms
class Solution { public: int calculate(string s) { if(s.empty()) return 0; int result = 0, sign = 1, num = 0; stack<int> stk; for(int i = 0; i < s.length(); i++){ if(s[i] <= '9' && s[i] >= '0') num = num * 10 + s[i] - '0'; else if(s[i] == '+' || s[i] == '-'){ result += num * sign; sign = (s[i] == '+' ? 1 : -1); num = 0; } else if(s[i] == '('){ stk.push(result); stk.push(sign); sign = 1; result = 0; } else if(s[i] == ')'){ result += num * sign; sign = stk.top(); stk.pop(); result = stk.top() + sign * result; stk.pop(); num = 0; } } if(num != 0) result += num * sign; return result; } };