fork download
  1. using System;
  2. using System.Linq;
  3.  
  4. public class RomanNumeral
  5. {
  6. const int NaN = -1;
  7. private static int ToInteger(string roman_numeral) {
  8. string ro_num = roman_numeral.ToUpper().Trim();
  9. char[] ro_num_array = ro_num.ToCharArray();
  10. if (ro_num == "N") { return 0; }
  11.  
  12. char[] symbols = { 'I', 'V', 'X', 'L', 'C', 'D', 'M' };
  13. int [] values = { 1, 5, 10, 50, 100, 500, 1000 };
  14. int int_num = 0;
  15. int symb_it = 0, symb_consec = 0;
  16.  
  17. bool to_parse = true;
  18. int subtrahend = 0, didgit = -1;
  19. foreach (char ro_num_char in ro_num_array.Reverse<char>()) {
  20. Console.WriteLine(ro_num_char);
  21. do
  22. {
  23. if (ro_num_char == symbols[symb_it])
  24. {
  25. symb_consec += (symb_it%2==1)? 3:1;
  26. if (symb_consec > 3) {
  27. Console.WriteLine("symb_consec>3");return NaN;
  28. }
  29. didgit = symb_it/2*2+2;
  30. Console.WriteLine("Didgit: " + didgit);
  31.  
  32. subtrahend = ((symb_it-1)/2)*2;
  33. int_num += values[symb_it];
  34. to_parse = false;
  35. Console.WriteLine(values[symb_it]);
  36. }
  37. else if ((ro_num_char == symbols[subtrahend]))
  38. {
  39. if (didgit == symb_it) { return NaN; }
  40. didgit = symb_it;
  41.  
  42. int_num -= values[subtrahend];
  43. to_parse = false;
  44. //Console.WriteLine(over_six);
  45. }
  46. if (to_parse) {
  47. symb_it++;
  48. if (symb_it > 6) { Console.WriteLine("symb_it>6");return NaN; }
  49. symb_consec = 0;
  50. }
  51. } while (to_parse);
  52.  
  53. to_parse = true;
  54. }
  55. return int_num;
  56. }
  57. public static void Main()
  58. {
  59. int test = RomanNumeral.ToInteger("MMCMXCIV");
  60. Console.WriteLine(String.Format("{0:D0}",test));
  61. }
  62. }
Success #stdin #stdout 0.05s 24040KB
stdin
Standard input is empty
stdout
V
Didgit: 2
5
I
C
Didgit: 6
100
X
M
Didgit: 8
1000
C
M
Didgit: 8
1000
M
Didgit: 8
1000
2994