2017-05-28 59 views
0

我尝试转换我的函数,它使用RomanNumeral Input将其作为Decimal Value从JS输出到C#,但以某种方式我卡住了,真的需要关于如何完成此工作的建议。尝试将JS函数转换为C#函数

using System; 
using System.Collections.Generic; 

class solution 
{ 

static int romanToDecimal(string romanNums) 
{ 
    int result = 0; 
    int [] deci = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 
    string [] roman = {"M", "CM", "D", "CD", "C", "XD", "L", "XL", "X", "IX", "V", "IV", "I"}; 

    for (var i = 0; i < deci.Length; i++) 
    { 
     while (romanNums.IndexOf(roman[i]) == 0) 
     { 
      result += deci[i]; 

      romanNums = romanNums.Replace(roman[i], " "); 
     }            
    }             
    return result;         
} 

static void Main() 
{ 

Console.WriteLine(romanToDecimal("V")); //Gibt 5 aus. 
Console.WriteLine(romanToDecimal("XIX")); // Gibt 19 aus. 
Console.WriteLine(romanToDecimal("MDXXVI"));// Gibt 1526 aus. 
Console.WriteLine(romanToDecimal("MCCCXXXVII"));// Gibt 1337 aus. 
} 

} 
+1

请解释为什么* *当前代码不起作用 – Rob

+0

我不认为XD是90 – RJM

+0

它应该是XC而不是 – Yatin

回答

2

不同的方式在C#替换工程,使用子串删除前几个字符匹配:

static int romanToDecimal(string romanNums) 
    { 
     int result = 0; 
     int[] deci = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 
     string[] roman = { "M", "CM", "D", "CD", "C", "XD", "L", "XL", "X", "IX", "V", "IV", "I" }; 

     for (var i = 0; i < deci.Length; i++) 
     { 
      while (romanNums.IndexOf(roman[i]) == 0) 
      { 
       result += deci[i]; 

       romanNums = romanNums.Substring(roman[i].Length); 
      } 
     } 
     return result; 
    } 
+0

非常感谢! –