Exemplo n.º 1
0
        public long Eval(string input)
        {
            input = input.Trim().Replace(" ", string.Empty);
            ValidateInput(input);

            var tokens = Tokenizer.Parse(input)
                         .Where(t => t.IsMathOperator || t.Type == TokenType.Number)
                         .ToList();

            var s = new Stack <Token>();

            foreach (var t in tokens)
            {
                if (t.IsMathOperator)
                {
                    s.Push(t);
                }
                else
                {
                    s.Push(t);
                    bool canProcess = true;
                    while (canProcess)
                    {
                        var t1 = s.Pop();
                        var t2 = s.Pop();
                        if (t2.Type == TokenType.Number)
                        {
                            var operation = s.Pop();
                            var r         = GetCalculation(t1, t2, operation);
                            s.Push(r);

                            if (s.Count == 1)
                            {
                                canProcess = false;
                            }
                        }
                        else
                        {
                            s.Push(t2);
                            s.Push(t1);
                            canProcess = false;
                        }
                    }
                }
            }

            return(s.Pop().Value.Value);
        }