12. Integer to Roman
来源:互联网 发布:布尔人 知乎 编辑:程序博客网 时间:2024/06/05 08:51
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
给定一个整数,将其转换为罗马数字。
保证输入在1到3999之间。
代码:
public class IntToRomanSolution { //我的方法 public static string IntToRoman(int num) { var dic1 = new Dictionary<int, string> { { 1, "I" }, { 2, "II" }, { 3, "III" }, { 4, "IV" }, { 5, "V" }, { 6, "VI" }, { 7, "VII" }, { 8, "VIII" }, { 9, "IX" }, { 0, "" } }; var dic10 = new Dictionary<int, string> { { 1, "X" }, { 2, "XX" }, { 3, "XXX" }, { 4, "XL" }, { 5, "L" }, { 6, "LX" }, { 7, "LXX" }, { 8, "LXXX" }, { 9, "XC" }, { 0, "" } }; var dic100 = new Dictionary<int, string> { { 1, "C" }, { 2, "CC" }, { 3, "CCC" }, { 4, "CD" }, { 5, "D" }, { 6, "DC" }, { 7, "DCC" }, { 8, "DCCC" }, { 9, "CM" }, { 0, "" } }; var dic1000 = new Dictionary<int, string> { { 1, "M" }, { 2, "MM" }, { 3, "MMM" }, { 0, "" } }; return dic1000[num / 1000 % 10] + dic100[num / 100 % 10] + dic10[num / 10 % 10] + dic1[num % 10]; } //好的方法 public static string IntToRoman2(int num) { int[] values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; string[] strs = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; string roman = ""; for (int i = 0; i < values.Length; i++) { while (num >= values[i]) { num -= values[i]; roman += strs[i]; } } return roman; } }
单元测试(通过):
[TestClass] public class UnitTest12_IntegerToRoman { [TestMethod] public void TestMethodIntToRoman() { Assert.AreEqual("MMMCMXCIX", IntToRomanSolution.IntToRoman(3999)); } [TestMethod] public void TestMethodIntToRoman2() { Assert.AreEqual("MMMCMXCIX", IntToRomanSolution.IntToRoman2(3999)); } }
阅读全文
0 0
- 12.Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- 12. Integer to Roman
- C语言文件操作lseek
- Linux后台Daemon中打印debug message的方法
- C语言指针的例题
- C++ 06 —— 拷贝构造函数
- 关于CSS的总结
- 12. Integer to Roman
- java 枚举
- 算法设计与应用基础
- LinkedBlockingQueue源码分析(JDK8)
- 使用Google与Chrome windows快捷键
- 以太坊和超级账本对比
- javascript系统时间设置
- MySQL的查询缓存功能现已成了瓶颈!
- 【问题收录】Ubuntu Starting LightDM Display Manager fail