企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
开发一款程序教小孩子认识罗马数字,小孩子已经对罗马数字非常熟悉了,但是不明白罗马数字的加法,在[面试技能六](http://blog.csdn.net/dotnetstudio/article/details/40111043)中已经对罗马数字的构成做了详细描述。现在做的程序也是在面试技能六的约束下,加法的求和最大限定在3000以内。 ~~~ /// <summary> /// 罗马数字转十进制数 /// </summary> /// <param name="number"></param> /// <returns></returns> public static int ConvertRomanToDecimal(string number) { Dictionary<string, int> dic = new Dictionary<string, int>(); dic.Add("M", 1000); dic.Add("CM", 900); dic.Add("D", 500); dic.Add("CD", 400); dic.Add("C", 100); dic.Add("XC", 90); dic.Add("L", 50); dic.Add("XL", 40); dic.Add("X", 10); dic.Add("IX", 9); dic.Add("V", 5); dic.Add("IV", 4); dic.Add("I", 1); int len = number.Length; if (len == 1) { return dic[number]; } if (len > 1) { int i = 0; int sum = 0; while (i < len) { int step = 1; if (len - i > 1) { step = 2; } string cnum = number.Substring(i, step); if (dic.ContainsKey(cnum)) { sum += dic[cnum]; i = i + step; } else { sum += dic[number.Substring(i, 1)]; i = i + 1; } } return sum; } return -1; } } ~~~ ~~~ /// <summary> /// 十进制转罗马数字 /// </summary> /// <param name="number"></param> /// <returns></returns> public static string ConvertDecimalToRoman(int number) { int[] decArray = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; string[] romAarry = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; int i = 0; string output = ""; while (number > 0) { while (number >= decArray[i]) { number = number - decArray[i]; output = output + romAarry[i]; } i++; } return output; } ~~~ ~~~ /// <summary> /// 加法器 /// </summary> /// <param name="s">输入罗马加法公式</param> /// <returns></returns> public static string RomanCalculator(string s) { string[] array = s.Split('+'); int sum = ConvertRomanToDecimal(array[0].Trim()) + ConvertRomanToDecimal(array[1].Trim()); return ConvertDecimalToRoman(sum); } ~~~ 调用RomanCalculator()函数,输入如下的测试数据进行测试。 Input                            Output XX + II                           XXII I + V                              VI II + II                             IV CCC + CCC               DC D + D                           M