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: don't use the eval
built-in library function.
Analytical:
Code parsing:
Package Leetcode;
Import Java.util.Stack;
No symbols, only the results of each step;
//main idea: to use +-as the number of positive and negative, push it to the stack (the last time the stack together by the addition of processing, priority is back, so after operation);
//when encountering */, only the last Num entered in the current NUM and stack is multiplied, and the result continues to be placed in the stack (/also the same) (priority is first, so the operation is preceded).
Fits this scene--stack
public class Basiccalculator {
public static int calculate (String s) {
int Len;
if (S==null | | (len = s.length ()) ==0) return 0;
stack<integer> stack = new stack<integer> ();
int num = 0;
Char sign = ' + ';
for (int i=0;i<len;i++) {
if (Character.isdigit (S.charat (i))) {
num = Num*10+s.charat (i)-' 0 ';
}
if ((! Character.isdigit (S.charat (i)) && "!=s.charat (i)) | | i==len-1) {
if (sign== '-') {
Stack.push (-num);
}
if (sign== ' + ') {
Stack.push (num);
}
//attention to pop and push methods
if (sign== ' * ') {
Stack.push (Stack.pop () *num);
}
if (sign== '/') {
Stack.push (Stack.pop ()/num);
}
Sign = S.charat (i);
num = 0;
}
}
int re = 0;
for (int i:stack) {
Re + = i;
}
return re;
}
public static void Main (string[] args) {
System.out.print (Calculate ("3+4-5*6/7"));
}
}
Leetcode-basic Calculator II