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.
我的答案:参考了前面224题
class Solution {
public:
int ret = 0;
int val1 = 0;
int val2 = 0;
bool more = false;
int sign = 1;
bool plus;
int calculate(string s) {
for (int pos=0; pos<s.size(); ++pos) {
char c = s[pos];
// cout << pos << ", " << c << ", ret = " << ret << ", val1 = " << val1 << ", val2 = " << val2 << ", more = " << more << ", plus = " << plus << endl;
if (isdigit(c)) {
if (!more) val1 = val1*10 + (c-'0');
else val2 = val2*10 + (c-'0');
}
else if (c == '+' or c == '-') {
section_end();
sign = (c == '+')? 1:-1;
clear();
}
else if (c == '*' or c == '/') {
if (more) {
val1 = plus? val1*val2:val1/val2;
}
more = true;
val2 = 0;
plus = (c == '*')? true:false;
}
}
section_end();
return ret;
}
void clear() {
val1 = 0;
val2 = 0;
more = false;
}
void section_end() {
if (more) {
val1 = plus? val1*val2:val1/val2;
}
ret += val1*sign;
}
};
Runtime: 8 ms, faster than 94.65% of C++ online submissions for Basic Calculator II.
Memory Usage: 8 MB, less than 94.35% of C++ online submissions for Basic Calculator II.
前面224是有括号,所以需要递归,这边主要是有*乘/除需要在+和-中间优先处理掉。我的方法是加一个plus的bool变量。这边有个小错误是,我只记得在主函数结尾处加了section_end里面的内容,忘记在(c == '+' or c == '-')
里面加了
网友评论