Problem 12: Integer to Roman

https://leetcode.com/problems/integer-to-roman/

思路

像做除法运算一样,提前把 千位数,百位数,个位数都存好,然后一位一位地求出来

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

易错点

  1. 每个String数组开始都有一个“”空字符串,这个位置是给0预备的

  2. M[num / 1000] + C[num % 1000 / 100] + X[num % 100 / 10] + I[num % 10]

    直接想的时候有时候会出现一些小的错误,如果能直接举例子,就会好很多了。eg: 3560,然后自己手动拿手除一下

Last updated