LeetCode -- Basic Calculator II

Source: Internet
Author: User

LeetCode -- Basic Calculator II
Description:


Implement a basic calculator to evaluate a simple expression string.


The expression string contains only non-negative integers, +,-, *,/operators and empty spaces. The integer division shoshould truncate toward zero.


You may assume that the given expression is always valid.


Some examples:
"3 + 2*2" = 7
"3/2" = 1
& Quot; 3 + 5/2 & quot; = 5


It is to parse the operands and operators for one expression, and perform four arithmetic operations, but not including parentheses.


Ideas:
1. Remove white space characters
2. Multi-digit words
3. If it is '*' or '/', calculate it directly; otherwise, the data is written into the stack.
4. Since only the addition and subtraction operators are left, the results can be calculated in order.




Implementation Code:


public int Calculate(string s){var exp = s.Where(c => c != ' ').ToList();var stackOp = new Stack
 
  ();var stackNum = new Stack
  
   ();var ops = new []{'+','-','*','/'};var n = "";for(var i = 0;i < exp.Count; i++){if(ops.Contains(exp[i])) // detected operator{stackOp.Push(exp[i]);}else{// parse the numberfor(var j = i;j < exp.Count; j++){if(!ops.Contains(exp[j])){n += exp[j];}else{break;}}var n1 = int.Parse(n);// if top is '*' or '/' , immediately calculateif(stackOp.Count > 0 && (stackOp.Peek() == '*' || stackOp.Peek() == '/')){var n2 = stackNum.Pop();stackNum.Push(Calc(n2, n1, stackOp.Pop()));}else{stackNum.Push(n1);}i += n.Length - 1;n = "";}}// since now we only left '+' and '-'// we should reverse the order (both operators and numbers) back to where they werevar stackOp1 = stackOp.Reverse();var stackNum1 = new Stack
   
    (stackNum);var count = 0;foreach(var op in stackOp1){var n1 = stackNum1.Pop();var n2 = stackNum1.Pop();stackNum1.Push(Calc(n1 , n2, op));count += 2;}return stackNum1.Pop();}private int Calc(int n1 , int n2, char op){switch(op){case '+':return n1 + n2;case '-':return n1 - n2;case '*':return n1 * n2;case '/':return n1 / n2;default :throw new ArgumentException(string.Format("unexpected operator : {0}", op));}}
   
  
 


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.