Problem:
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +
, -
, *
, /
operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" =
" 3/2 " =
" 3+5 / 2 " =
Note: Do not use the eval
built-in library function.
Solution:
字符串分成两种情况:数字num和运算符op,结果设为res,考虑到先乘除后加减的运算法则,设中间数mid优先计算乘除,再与res相加.
*> C++ version
class Solution {
public:
int calculate(string s)
{
int res=, num=, op='+', i=, mid=;
while(i<s.size())
{
num = ; ////每一轮要初始化num
//获取一整个数字存储在num中
if(isdigit(s[i]))
{
while(i<s.size()&&isdigit(s[i])) //连续数字字符作一个数
{
num = num*+(s[i]-'');
i++;
} //获取运算符存储在op中
if(op=='+'||op=='-')
{
res = res+mid;
mid = num*(op=='-'?-:);
}
else if(op=='/')
{
mid = mid/num;
}
else if(op=='*')
{
mid = mid*num;
}
}
else if(s[i]==' ') //不要漏了开头空格这种情况= - =它喵被摆了一道
i++;
else
{
op=s[i];
i++;
}
}
res = res+mid;
return res;
}
};