首页 > 代码库 > 12. Integer to Roman

12. Integer to Roman

题目

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.


分析

整数转化为罗马数字字符串

 

罗马数字

采用七个罗马字母作数字、即Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。

有两条须注意掌握:
  1. 基本数字 Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边采用相加的方式构成数目,都不能超过三个;放在大数的左边采用相减的方式构成数目,只能用一个;
  2. 基本数字 V 、L 、D 中的任何一个,放在大数的右边采用相加的方式构成数目、只能使用一个;不能放在大数的左边采用相减的方式构成数目

举例:

个位数
Ⅰ-1、Ⅱ-2、Ⅲ-3、Ⅳ-4、Ⅴ-5、Ⅵ-6、Ⅶ-7、Ⅷ-8、Ⅸ-9
十位数
X-10、Ⅺ-11、Ⅻ-12、XIII-13、XIV-14、XV-15、XVI-16、XVII-17、XVIII-18、XIX-19、XX-20、XXI-21、XXII-22、XXIX-29、XXX-30、XXXIV-34、XXXV-35、XXXIX-39、XL-40、L-50、LI-51、LV-55、LX-60、LXV-65、LXXX-80、XC-90、XCIII-93、XCV-95、XCVIII-98、XCIX-99
百位数
C-100、CC-200、CCC-300、CD-400、D-500、DC-600、DCC-700、DCCC-800、CM-900、CMXCIX-999
千位数
M-1000、MC-1100、MCD-1400、MD-1500、MDC-1600、MDCLXVI-1666、MDCCCLXXXVIII-1888、MDCCCXCIX-1899、MCM-1900、MCMLXXVI-1976、MCMLXXXIV-1984、MCMXC-1990、MM-2000、MMMCMXCIX-3999

 

千位:M-1000、MM-2000、MMM-3000

百位:C-100、CC-200、CCC-300、CD-400、D-500、DC-600、DCC-700、DCCC-800、CM-900

十位:X-10、XX-20、XXX-30、XL-40、L-50、LX-60、LXX-70、LXXX-80、XC-90

个位:I-1、II-2、III-3、IV-4、V-5、VI-6、VII-7、VIII-8、IX-9


解答

解法1:(我)列出罗马数字千位、百位、十位、个位的字符串数组,根据输入整数每一位从中选择字符串(108ms)

public class Solution {
    public String intToRoman(int num) {
        String roman[][] = {{"M","MM","MMM"},{"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},{"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},{"I","II","III","IV","V","VI","VII","VIII","IX"}};
        String result = "";
        for (int i = 0; i < 4; i++){
            int power = (int)Math.pow(10,3-i);
            result += (num/power > 0) ? roman[i][num/power-1] : "";
            num -= num/power * power;
        }

        return result;
    }
}

解法2:解法1的简化(105ms√)

1. 每一位的数组第一项加上"",省去了该位是否大于0的判断

2. 使用余数

public class Solution {
    public String intToRoman(int num) {
        String roman[][] = {{"","M","MM","MMM"},{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},{"","I","II","III","IV","V","VI","VII","VIII","IX"}};
        String result = "";
        result += (roman[0][num / 1000] + roman[1][num % 1000 / 100] + roman[2][num % 100 / 10] + roman[3][num % 10]);

        return result;
    }
}

 

12. Integer to Roman