Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Algo
- {
- class Program
- {
- static int Evaluate2(string expr)
- {
- Stack<char> op = new Stack<char>();
- Stack<int> nums = new Stack<int>();
- foreach (var ch in expr)
- {
- if (ch == '+' || ch == '*')
- {
- op.Push(ch);
- }
- else if (ch >= '0' && ch <= '9')
- {
- nums.Push(ch - '0');
- }
- else if (ch == '(')
- {
- nums.Push('(');
- }
- else if (ch == ')')
- {
- int result = 0;
- if (op.Peek() == '+')
- {
- while (nums.Peek() != '(')
- {
- result += nums.Peek();
- nums.Pop();
- }
- }
- else if (op.Peek() == '*')
- {
- result = 1;
- while (nums.Peek() != '(')
- {
- result *= nums.Peek();
- nums.Pop();
- }
- }
- nums.Pop(); // remove (
- nums.Push(result);
- op.Pop();
- }
- }
- return nums.Peek();
- }
- static int Evaluate1(string expr)
- {
- Stack<char> op = new Stack<char>();
- Stack<int> nums = new Stack<int>();
- foreach (var ch in expr)
- {
- if (ch == '+' || ch == '*')
- {
- op.Push(ch);
- }
- else if (ch >= '0' && ch <= '9')
- {
- nums.Push(ch - '0');
- }
- else if (ch == ')')
- {
- char oper = op.Pop();
- int result = 0;
- if (oper == '+')
- {
- result = nums.Pop() + nums.Pop();
- }
- else if (oper == '*')
- {
- result = nums.Pop() * nums.Pop();
- }
- nums.Push(result);
- }
- }
- return nums.Peek();
- }
- static void Main(string[] args)
- {
- Console.WriteLine(Evaluate1("+(2,*(3,8))"));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement