c# - I am trying to figure out how to convert roman numerals into integers -


i trying figure out how convert roman numerals integers. portion of code. when prompt user enter m shows 1000, when prompt user enter roman numeral such vm, not give me 995 instead 1005. because telling program that.

what trying figure out how can ahead , know when adding or subtracting roman numerals.

how begin go doing this?

class roman {      public int inprogress = 0;     public roman(string roman)     {          char temp = 'z';         int length;          length = roman.length;          (int = 0; < length; i++)         {             temp = roman[i];             if (temp == 'm')             {                 inprogress = inprogress + 1000;             }             if (temp == 'd')             {                 inprogress = inprogress + 500;             }             if (temp == 'c')             {                 inprogress = inprogress + 100;             }             if (temp == 'l')             {                 inprogress = inprogress + 50;             }             if (temp == 'x')             {                 inprogress = inprogress + 10;             }             if (temp == 'v')             {                 inprogress = inprogress + 5;             }             if (temp == 'i')             {                 inprogress = inprogress + 1;             }         }     } } 

the trick converting roman numerals work backwards (from end of string) not forwards, makes lot easier.

eg, if have ix

  • you start x, = 10
  • move 1.... i, less x subtract off 1 = 9

a reference solution....

public class romannumeral     {         public static int toint(string s)         {               var last = 0;               return s.reverse().select(numeralvalue).sum(v =>               {                                     var r = (v >= last)? v : -v;                 last = v;                 return r;               });         }          private static int numeralvalue(char c)         {             switch (c)             {                 case 'i': return 1;                 case 'v': return 5;                 case 'x': return 10;                 case 'l': return 50;                 case 'c': return 100;                 case 'd': return 500;                 case 'm': return 1000;                                 }             return 0;         }     } 

note: doesn't validate roman numerals, convert ones valid.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -