fork(4) download
  1. using System;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. using System.Linq;
  5.  
  6. class Program
  7. {
  8. static void Main()
  9. {
  10. string expr = "50*2+1";
  11. string[] num = Regex.Split(expr, @"\-|\+|\*|\/").Where(s => !String.IsNullOrEmpty(s)).ToArray(); // get Array for numbers
  12. string[] op = Regex.Split(expr, @"\d{1,3}").Where(s => !String.IsNullOrEmpty(s)).ToArray(); // get Array for mathematical operators +,-,/,*
  13. int numCtr = 0, lastVal=0; // number counter and last Value accumulator
  14. string lastOp = ""; // last Operator
  15. foreach (string n in num)
  16. {
  17. numCtr++;
  18. if (numCtr == 1)
  19. {
  20. lastVal = int.Parse(n); // if first loop lastVal will have the first numeric value
  21. }
  22. else
  23. {
  24. if (!String.IsNullOrEmpty(lastOp)) // if last Operator not empty
  25. {
  26. // Do the mathematical computation and accumulation
  27. switch (lastOp)
  28. {
  29. case "+":
  30. lastVal = lastVal + int.Parse(n);
  31. break;
  32. case "-":
  33. lastVal = lastVal - int.Parse(n);
  34. break;
  35. case "*":
  36. lastVal = lastVal * int.Parse(n);
  37. break;
  38. case "/":
  39. lastVal = lastVal + int.Parse(n);
  40. break;
  41.  
  42. }
  43. }
  44. }
  45. int opCtr = 0;
  46. foreach (string o in op)
  47. {
  48. opCtr++;
  49. if (opCtr == numCtr) //will make sure it will get the next operator
  50. {
  51. lastOp = o; // get the last operator
  52. break;
  53. }
  54. }
  55. }
  56. Console.WriteLine(lastVal.ToString());
  57. }
  58. }
Success #stdin #stdout 0.09s 34096KB
stdin
Standard input is empty
stdout
101