Topic
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
A calculator that contains no parentheses, with spaces
Ideas
Take a stack implementation. Scan strings from beginning to end:
- If it is a number, as the current members, the previous number left one as a high.
- If it is a symbol, if you add and subtract, multiply the number by the symbol into the stack.
- If it is the multiplication method, a number is ejected from the stack, multiplied by the current number, in addition to pressing back to the stack.
Note that using a suffix expression, read out the two numbers in the read-out symbol, in the order:
- The initial value of the previous symbol is + (because when the first symbol is read, the operation on the first number must be pressed into the stack, the same as the + case)
- Read a number and press it into the stack
- read out a symbol
- Reading out a number
- Determines the current operation based on the previous symbol
- When the operation is complete, the symbol you just read is recorded as the previous symbol.
This is equivalent to completing the conversion of the normal expression to the suffix expression.
Code
classSolution { Public: intCalculatestrings) {stack<int>Mystack; CharSign ='+'; intnum =0, res=0; for(inti =0; I < s.size (); i++){ if(IsDigit (s[i]) num= num *Ten+ S[i]-'0'; if(((!isdigit (s[i)) && (!isspace (s[i))) | | (I==s.size ()-1)){ if(Sign = ='+') Mystack.push (num); if(Sign = ='-') Mystack.push (Num*-1); if(Sign = ='*') {num= Mystack.top () *num; Mystack.pop (); Mystack.push (num); } if(Sign = ='/') {num= Mystack.top ()/num; Mystack.pop (); Mystack.push (num); } Sign=S[i]; Num=0; } } while(!Mystack.empty ()) {Res+=Mystack.top (); Mystack.pop (); } returnRes; }};
Other
About "Ctype.h"
Images from Wikipedia
Leetcode#227.basic Calculator II