Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open (
and closing parentheses )
, the plus +
or minus sign -
, Non-ne gative integers and empty spaces
.
Assume that the given expression was always valid.
Some Examples:
"1 + 1" = 2 "2-1 + 2" = 3 "(1+ (4+5+2)-3) + (6+8)" = 23
Note: don't use the eval
built-in library function.
Problem Solving Ideas:
You only need to identify the symbols that need to be brought in after each parenthesis, with a stack, and the Java implementation is as follows:
public int Calculate (String s) {stack<integer> sign = new stack<integer> (); Sign.push (1); int lastop = 1;int Res = 0;for (int i = 0; i < s.length (); i++) {switch (S.charat (i)) {case ": break;case ' + ': lastop = 1;break;case '-': Last Op = -1;break;case ' (': Sign.push (Lastop*sign.peek ()); Lastop=1;break;case ') ': Sign.pop (); Break;default:int num = 0; while (I < s.length () && character.isdigit (S.charat (i)) num = num * + s.charat (i++)-' 0 '; I--;res + = Lastop * num * Sign.peek ();}} return res; }
Java for Leetcode 224 Basic Calculator