Leetcode Problem solving note, basic calculator 1&&basic Calculator 2

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.