Java for Leetcode 224 Basic Calculator

Source: Internet
Author: User

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

Related Article

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.