[Leetcode] Basic Calculator

Source: Internet
Author: User

Basic Calculator

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

Note:do not use the eval built-in library function.

Using the stack, if you encounter an opening parenthesis ' (' press the previous value and the 1.-1 expression operation symbol into the stack, you encounter a closing parenthesis ') ', the operation symbol and value removal are calculated.

1 classSolution {2  Public:3     intCalculatestrings) {4         if(s.length () = =0)return 0;5stack<int>Mystack;6         intresult=0;7         intop=1;8          for(intI=0; I<s.length (); i++)9         {Ten             if(s[i]>='0'&& s[i]<='9') One             { A                 intnumber=s[i]-'0'; -                  while((i+1) <s.length () && s[i+1]>='0'&& s[i+1]<='9') -                 { thei++; -number=number*Ten+s[i]-'0'; -                 } -result+=op*Number ; +             } -             if(s[i]==' ') +             { A                 Continue; at             } -             if(s[i]=='+') -             { -op=1; -             } -             if(s[i]=='-') in             { -op=-1; to             } +             if(s[i]=='(') -             { the Mystack.push (result); *result=0; $ Mystack.push (OP);Panax Notoginsengop=1; -             } the             if(s[i]==')') +             { Aop=mystack.top (); the Mystack.pop (); +result=op*result+mystack.top (); - Mystack.pop (); $op=1; $             } -         } -         returnresult; the     } -};

[Leetcode]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.