Problem description
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.
Program
The first is the normal way: first, the expression is converted to a suffix expression, and then evaluated. (TLE)
The second is a simplified method, more ingenious.
public class Basiccalculator {public int calculate (String s) {if (s = = NULL | | s.length () = = 0) {return 0;} Preprocesss = S.trim (); char[] cc = S.tochararray (); String new_s = ""; for (int i = 0; i < cc.length; i++) {if (cc[i] = = ' (' | | cc[i] = = ') ') {continue;} if (cc[i] = = ' + ' | | cc[i] = = '-') {new_s + = "" + Cc[i] + "";} else {new_s + = Cc[i];}} string[] items = New_s.split (""); list<string> postexpressionlist = new arraylist<string> (); Stack<string> st = new Stack<string> ();//Transform to postfix expressionfor (int i = 0; i < items.length; i++) {String item = Items[i].trim (); if (item.length () = = 0) {continue;} if (item.equals ("+") | | | item.equals ("-")) {if (!st.isempty ()) {Postexpressionlist.add (St.pop ());} St.push (item);} else {Postexpressionlist.add (item);}} while (!st.isempty ()) {Postexpressionlist.add (St.pop ());} calculatestack<integer> calstack = new stack<integer> (); for (String ex:postexpressionlist) {if (ex.equal S ("+")) {int N1 = CalstaCk.pop (); int n2 = Calstack.pop (); Calstack.push (n1 + n2);} else if (ex.equals ("-")) {int N1 = Calstack.pop (); int n2 = Calstack.pop (); Calstack.push (N2-N1);} else {calstack.push (int Eger.valueof (ex));}} return Calstack.peek ();} public int Calculate2 (String s) {if (s = = NULL | | s.length () = = 0) {return 0;} s = S.trim (); int res = 0, sign = 1; stack<integer> st= new stack<integer> (); for (int i = 0; i < s.length (); i++) {char c = s.charat (i); if (char Acter.isdigit (c)) {int cur = c-' 0 '; while (I+1 < s.length () && character.isdigit (S.charat (i+1))) {cur = cur * Ten + (S.charat (i+1)-' 0 '); ++i;} Res + = sign * cur;} else if (c = = ' + ') {sign = 1;} else if (c = = '-') {sign =-1;} else if (c = = ' (') {St.push (res); res = 0;st.push (sign); sign = 1;} else if (c = = ') ') {res = St.pop () *res + st.pop (); sign = 1;}} return res;}}
Basic Calculator I