Integer to Roman

Description

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

将整型转换成罗马数字形式:

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

Solution

因为限定了范围,所以千位数也用了Slice

1
2
3
4
5
6
7
8
func intToRoman(num int) string {
    M := []string{"", "M", "MM", "MMM"}
    C := []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
    X := []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
    I := []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}

    return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10]
}

Similar Problem

13. Integer to Roman