You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "3+2*2"
Output: 7
Example 2:
Input: s = " 3/2 "
Output: 1
Example 3:
Input: s = " 3+5 / 2 "
Output: 5
/** * @param {string} s * @return {number} */varcalculate=function(s){letstack=[];letnum='';letsign=null// we loop till the full length of the array to account for last signfor(leti=0;i<=s.length;i++){constcurr=s[i];//handle spaceif(curr===' ')continue;//if char is a numberif(!isNaN(curr))num+=curr;//if we have a sign + - / *if(isNaN(curr)){num=Number(num)switch(sign){case'+':
casenull:
//we push the initial number into the stackstack.push(num)break;case'-':
//we push any values after the subtraction sign as negativestack.push(-num)break;case'*':
//we pop the stack then multiply and push backstack.push(stack.pop()*num)break;case'/':
//we pop the stack then devide and push backstack.push(parseInt(stack.pop()/num,10))break;}// sign becomes current signsign=curr;// we reset numnum='';}}//we reduce the array adding positive and negative numbersreturnstack.reduce((a,b)=>{returna+b},0)};