Leetcode oj:basic Calculator (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-negati ve 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

A basic calculator, you can use two stacks to solve, the following method is to refer to other people's practice, when you encounter the opening parenthesis to consider the first thing in parentheses, so the previous results all into the stack. When the closing parenthesis is encountered, the stack's contents before the opening parenthesis are calculated to get the temporary result again. here because

After that there is a + and minus sign, so you can use sign = =-to simulate minus. The res here actually corresponds to the role of a stack:

1 classSolution {2  Public:3     intCalculatestrings) {4         intSZ =s.size ();5         intLeft , right;6         CharOptor ='0';7stack<int> TOKENSTK;//Note that this is int8         intres =0;9         intSign =1;Ten          for(inti =0; I < sz; ++i) { One             if(S[i] = ='+') ASign =1; -             Else if(S[i] = ='-') -Sign =-1; the             Else if(IsDigit (S[i])) { -                 intTmpnum =0; -                  for(intj = i; J < Sz; ++j) { -                     if(IsDigit (S[j])) { +Tmpnum *=Ten; -Tmpnum + = (S[j]-'0'); +i =J; A}Else  Break; at                 } -Res + = sign *Tmpnum; -}Else if(S[i] = ='('){ - Tokenstk.push (res); -res =0; - Tokenstk.push (sign); inSign =1; -}Else if(S[i] = =')'){ to                 intTmpsign =tokenstk.top (); + Tokenstk.pop (); -                 intleft =tokenstk.top (); the Tokenstk.pop (); *res = res * tmpsign +Left ; $Sign =1;Panax Notoginseng             } -         } the         returnRes; +     } A};

Leetcode oj:basic Calculator (Basic calculator)

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.