Basic Calculator1
Topic content:
Implement a small calculator with add and subtract and parentheses, where the input is not negative, and the input is all legal expressions.
Personal analysis:
1. Use stack to solve the problem and put the resulting temporary results into the stack
2. Insert result into stack when the parentheses are encountered
Experience:
1. For the addition and subtraction can be directly using symbols to operate, specifically set a sign of the variable to save this symbol
2. Fixed number of numbers in conversion string: # = Number*10+s.charat (i)-' 0 '
3. For this kind of need to record the intermediate process can be achieved using the stack, similar topics have valid pathness (judging the legal symbol)
4. Control of symbols can be manipulated using pop or push.
5. When the result results are put into the stack, the result results should be re-assigned result=0;
Code:
public int Calculate (String s) {
stack<integer> stack = new stack<integer> ();
int result = 0;
int num = 0;
int sign = 1;
for (int i=0; i<s.length (); i++) {
if (Character.isdigit (S.charat (i))) {
num = Num*10+s.charat (i)-' 0 ';
}else if (S.charat (i) = = ' + ') {
result + = Num*sign;
num = 0;
sign = 1;
}else if (S.charat (i) = = '-') {
Result +=num*sign;
num = 0;
sign =-1;
}else if (S.charat (i) = = ' (') {
Stack.push (result);
Stack.push (sign);
result = 0;
sign = 1;
}else if (S.charat (i) = = ') ') {
result + = Sign*num;
num = 0;
Result *= Stack.pop ();
Result + = Stack.pop ();
}
}
if (num!=0) result +=sign*num;
return result;
}
Basic Calculator2:
1. Different from 1, the calculation results are all put in the stack and finally added and calculated
Leetcode problem-solving notes, basic calculator 1&&basic Calculator 2