數字轉羅馬文字,4 & 9 有特例
,除 千 百 十 及餘 取係數出來,如果係數== 9 or 4 就固定某個roman number,不是就 repeat 係數/5的次數 及 repeate 係數% 5的次數,全部加起來就是了
1 public string IntToRoman(int num) 2 { 3 string result = string.Empty; 4 //千位 5 var thun = num / 1000; 6 //百位 7 var hun = (num = (num - (thun * 1000))) / 100; 8 //十位 9 var ten = (num = (num - (hun * 100))) / 10; 10 //個位 11 var remain = num % 10; 12 13 result += string.Join("", Enumerable.Repeat("M", thun)); 14 15 if (hun == 9) 16 result += "CM"; 17 else if (hun == 4) 18 result += "CD"; 19 else 20 { 21 //500的重複 22 result += string.Join("", Enumerable.Repeat("D", hun / 5)); 23 //小於500的重複 24 result += string.Join("", Enumerable.Repeat("C", hun % 5)); 25 } 26 27 if (ten == 9) 28 result += "XC"; 29 else if (ten == 4) 30 result += "XL"; 31 else 32 { 33 //50的重複 34 result += string.Join("", Enumerable.Repeat("L", ten / 5)); 35 //小於50的重複 36 result += string.Join("", Enumerable.Repeat("X", ten % 5)); 37 } 38 39 if (remain == 9) 40 result += "IX"; 41 else if (remain == 4) 42 result += "IV"; 43 else 44 { 45 //5的重複 46 result += string.Join("", Enumerable.Repeat("V", remain / 5)); 47 //小於5的重複 48 result += string.Join("", Enumerable.Repeat("I", remain % 5)); 49 } 50 51 return result; 52 }