### 题目

Given an integer, convert it to a roman numeral.

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

### 二维数组记录所有

300 = CCC
20 = XX
7 = VII

327 = CCCXXVII


["","I","II","III","IV","V","VI","VII","VIII","IX"] // 0,1,2,3,...,9
["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"] // 0,10,20,30,...,90
["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"] // 0,100,200,300,...,900
["","M","MM","MMM",null,null,null,null,null,null] // 0,1000,2000,3000


#### 代码

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


### 写一套规则，自动拼装

#### 代码

public class Solution {
private static final char[][] SYM = new char[][] {
{'I','V','X'},
{'X','L','C'},
{'C','D','M'},
{'M',Character.MIN_VALUE,Character.MIN_VALUE}
};
public String intToRoman(int num) {
int carry = 0;
StringBuilder sb = new StringBuilder();
while (num > 0) { // 327 = [7,2,3,0]
generate(num%10,SYM[carry++],sb);
num = num/10;
}
return sb.toString();
}
public void generate(int num, char[] symbol, StringBuilder sb) { // num = [0...9]
StringBuilder temp = new StringBuilder();
if (num < 4) {
for (int i = 0; i < num; i++) {
temp = temp.append(symbol[0]);
}
} else if (num == 4) {
temp = temp.append(symbol[0]).append(symbol[1]);
} else if (num < 9) {
temp = temp.append(symbol[1]);
for (int i = 0; i< num-5; i++) {
temp = temp.append(symbol[0]);
}
} else if (num == 9) {
temp = temp.append(symbol[0]).append(symbol[2]);
} else {
throw new NumberFormatException();
}
sb = sb.insert(0,temp);
}
}


### 最简短的查表法

#### 代码

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