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
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决定);
继续以上步骤,直到遍历到字符串的最后一个字符
class Solution {
public:
int calculate(string s)
{
stack<int> st;
int sign = 1;
int num = 0;
int result = 0;
for(int i = 0; i < s.size(); ++i)
{
if(s[i] >= '0' && s[i] <= '9')
{
num = 10 * num + (s[i] - '0');
}else if(s[i] == '+')
{
result += sign * num;
sign = 1;
num = 0;
}else if(s[i] == '-')
{
result += sign * num;
sign = -1;
num = 0;
}else if(s[i] == '(')
{
//result += sign * num;
//st.push(sign);
st.push(result);
st.push(sign);
sign = 1;
result = 0;
//num = 0;
}else if(s[i] == ')')
{
result += sign * num;
int sig = st.top();
st.pop();
int res = st.top();
st.pop();
result = res + sig * result;
sign = 1;
num = 0;
}
}
if(num != 0)
{
result += sign * num;
}
return result;
}
};