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.
Assume that the given expression was always valid.
Some Examples:
"3+2*2" = 7 "3/2" = 1 "3+5/2" = 5
Note:do not use the eval built-in library function.
==================
Basic +,-, *,/calculations, leveraging stacks
====
Ideas:
Apply two stacks, a symbol stack op, a number stack num,
Code:
classSolution { Public: intCalculatestrings) {stack<Char>op; Stack<int>num; Const intn =s.size (); Charch; intTMP =0; intA =0; for(inti =0; i<n;i++) {ch=S[i]; if(ch==' ')Continue; Else if(ch=='*'|| ch=='/'|| ch=='+'|| ch=='-') {op.push (CH); }Else if(IsDigit (CH)) {tmp= tmp*Ten+ch-'0'; while(I<n && isdigit (ch=s[++i])) {tmp= tmp*Ten+ch-'0'; } if(!Op.empty ()) { CharCurr_op =Op.top (); if(Curr_op = ='*'){ intA =num.top (); Num.pop (); Op.pop (); Num.push (A*tmp); }Else if(Curr_op = ='/') {a=num.top (); Num.pop (); Op.pop (); Num.push (A/tmp); }Else{ if(Curr_op = ='-') TMP *=-1; Num.push (TMP); } }Else{Num.push (TMP); } tmp=0; if(i==n) Break; I--; } } while(!Op.empty ()) { intA =num.top (); Num.pop (); intb =num.top (); Num.pop (); //char ch = op.top ();Op.pop (); Num.push (A+b); }/// while intRe =num.top (); Num.pop (); returnre; }};
227. Basic Calculator II