leetcode:https://leetcode-cn.com/problems/calculator-lcci/
示例 1:
输入: "3+2*2"
输出: 7
示例 2:
输入: " 3/2 "
输出: 1
示例 3:
输入: " 3+5 / 2 "
输出: 5
没什么思路可言,直接上代码!
var calculate = function(s) {
let prev = 0, num = 0, sum = 0, preOp = '+'
s += '&'
for(let i=0; i < s.length; i++) {
if(s[i] == ' ') continue;
if(/\d/.test(s[i])) {
let base = 10, v = Number(s[i]);
while(/\d/.test(s[i+1])) && i+1 < s.length) {
v = base * v + Number(s[i+1]);
i++;
}
num = v;
}
else {
switch(preOp) {
case '+' :
sum += prev;
prev = num;
break;
case '-':
sum += prev;
prev -= num;
break;
case '*':
prev *= num
break;
case '/':
prev /= num;
prev = Math.trunc(prev);
break;
}
preOp = s[i];
num = 0;
}
}
return prev + sum;
}
实在是高手