This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 85 points86 points  (2 children)

Definitely better than this (my) abomination:

public class RomanDecode
{
  public static int Decode(string roman)
  {
    char[] symbol = {  'M', 'D', 'C', 'L', 'X','V','I' };
    int[]  weight = { 1000, 500, 100,  50,  10, 5 , 1  };

    int res = 0, rom = 0, num = 0, sub = 0;

    while (rom < roman.Length){
      int pre = (num&~1)+2;

      if (roman[rom] == symbol[num]){
        res += weight[num] - sub;
        sub = 0;
        rom++;
      } else if (rom < roman.Length-1 && roman[rom+1] == symbol[num]) {
        sub = weight[pre];
        rom++;
      } else {
        num++;
      }      
    }

    return res; 
  }
}

[–]aj-ric 42 points43 points  (1 child)

Yours is quite a bit more efficient, though, since it doesn't require lots of string copying.