fork download
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. public class Test
  5. {
  6. public static int Eval(string exp)
  7. {
  8. Stack<char> operators=new Stack<char>();
  9. Stack<int> operand=new Stack<int>();
  10. for(int i=0;i<exp.Length;i++)
  11. {
  12. char ch=exp[i];
  13. if(new List<char>{'(','+','-','*'}.Contains(ch))
  14. operators.Push(ch);
  15. else
  16. if(ch==')')
  17. {
  18. char op=operators.Pop();
  19. if(op=='(') continue;
  20. int b=operand.Pop(),a=operand.Pop();
  21. if(op=='+') operand.Push(a+b);
  22. if(op=='-') operand.Push(a-b);
  23. if(op=='*') operand.Push(a*b);
  24. }
  25. else { int a=exp[i]-'0';
  26. List<char> dig=new List<char>{'0','1','2','3','4','5','6','7','8','9'};
  27. while( dig.Contains(exp[i+1]))
  28. {
  29. i++;
  30. a=a*10+(exp[i]-'0');
  31. }
  32. operand.Push(a);
  33. }
  34. }
  35. return operand.Pop();
  36. }
  37. public static void Main()
  38. {
  39. // your code goes here
  40. Console.WriteLine(Eval("(2*(3-(4*5)))"));
  41. }
  42. }
Success #stdin #stdout 0.03s 25412KB
stdin
Standard input is empty
stdout
-17