LeetCode: 227. Basic Calculator II
题目描述
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.
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
Input: " 3+5 / 2 "
Output: 5
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function.
解题思路
将单个数字和乘除法作为加法运算的 “项(item)”,每次获取下一项进行计算。
AC 代码
class Solution {
private:
int Op(char op, int lhv, int rhv)
{
if(op == '+') return lhv+rhv;
else if(op == '-') return lhv-rhv;
else if(op == '*') return lhv*rhv;
else return lhv/rhv;
}
// idx, result
pair<int, int> nextItem(string str, int beg)
{
int result = 0;
int curNum = 0;
char op = '+';
size_t i;
size_t pos = str.find_first_of("+-", beg);
if(pos == str.npos) pos = str.size();
for(i = beg; i <= pos; ++i)
{
if(str[i] == ' ') continue;
if(i == pos)
{
result = Op(op, result, curNum);
break;
}
if(str[i] >= '0' && str[i] <= '9')
{
curNum = curNum*10+str[i]-'0';
}
else if(str[i] == '*' || str[i] == '/')
{
result = Op(op, result, curNum);
op = str[i];
curNum = 0;
}
}
return {i, result};
}
public:
int calculate(string s) {
int result = 0;
int curNum = 0;
int idx = 0;
char op = '+';
pair<int, int> curPair{0,0};
while(idx < s.size())
{
if(s[idx] == ' ')
{
++idx;
continue;
}
if(s[idx] =='+' || s[idx] =='-')
{
op = s[idx++];
continue;
}
curPair = nextItem(s, idx);
result = Op(op, result, curPair.second);
idx = curPair.first;
}
return result;
}
};