题目描述
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。 X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。
示例:
输入: 1994 输出: "MCMXCIV" 解释: M = 1000, CM = 900, XC = 90, IV = 4.
思路
1.这道题本质上是贪心算法,从大到小依次转换。
2.可以将罗马数字和阿拉伯数字放到两个对应的数组里,这样方便操作。
Java代码实现
/** * 方法一:简易式写法 * @param num * @return */ public String intToRoman(int num) { String romanStr = ""; while(num >= 1000){ romanStr += "M"; num -= 1000; } while(num >= 900){ romanStr += "CM"; num -= 900; } while(num >= 500){ romanStr += "D"; num -= 500; } while(num >= 400){ romanStr += "CD"; num -= 400; } while(num >= 100){ romanStr += "C"; num -= 100; } while(num >= 90){ romanStr += "XC"; num -= 90; } while(num >= 50){ romanStr += "L"; num -= 50; } while(num >= 40){ romanStr += "XL"; num -= 40; } while(num >= 10){ romanStr += "X"; num -= 10; } while(num >= 9){ romanStr += "IX"; num -= 9; } while(num >= 5){ romanStr += "V"; num -= 5; } while(num >= 4){ romanStr += "IV"; num -= 4; } while(num > 0){ romanStr += "I"; num -= 1; } return romanStr; } /** * 方法二:略微优雅式写法 * @param num * @return */ public String intToRoman(int num) { int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; String romanStr = ""; int index = 0; while(index<13){ while(num>=nums[index]){ romanStr += romans[index]; num = num - nums[index]; } index++; } return romanStr; }
Golang代码实现1
func intToRoman(num int) string { res := "" for num != 0 { for num/1000 > 0{ res = res + "M" num = num - 1000 } for num/900 > 0{ res = res + "CM" num = num - 900 } for num/500 > 0{ res = res + "D" num = num - 500 } for num/400 > 0{ res = res + "CD" num = num - 400 } for num/100 > 0{ res = res + "C" num = num - 100 } for num/90 > 0{ res = res + "XC" num = num - 90 } for num/50 > 0{ res = res + "L" num = num - 50 } for num/40 > 0{ res = res + "XL" num = num - 40 } for num/10 > 0{ res = res + "X" num = num - 10 } for num/9 > 0{ res = res + "IX" num = num - 9 } for num/5 > 0{ res = res + "V" num = num - 5 } for num/4 > 0{ res = res + "IV" num = num - 4 } for num/1 > 0{ res = res + "I" num = num - 1 } } return res }
Golang代码实现2
func intToRoman(num int) string { res := "" romans := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"} numbers := []int{1000,900,500,400,100,90,50,40,10,9,5,4,1} for i:=0;i< len(romans) && num > 0;i++ { for num >= numbers[i] { res += romans[i] num -= numbers[i] } } return res }