2017-05-28 31 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

非常感謝! –