Integer To Roman Numeral
- Medium
- tag: math
- similar: isomorphic strings, roman
int to roman. $$int \in [0,3999]$$
思考
- 之前做了roman to integer, 发现了从后向前loop能避免分情况考虑. 这是因为左边小的时候是想减的. 于是发现了一个规律, 只要把这种想减的情况挑出来就很容易了. 先找一下规律.
- 看int 2 roman表
- 发现循环的这几个: 1,4,5,9,10,40,50,90,100,400,500,900,1000.
idea
- 先写出上面这些特殊情况, 然后从大到小的loop即可.
- 代码如下:
public String intToRoman(int num) {
if (num < 0 || num > 3999) {
return "INVALID";
}
String[] strs =
new String[] {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int[] vals = new int[] {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < vals.length; ++i) {
while (num >= vals[i]) {
num -= vals[i];
sb.append(strs[i]);
}
}
return sb.toString();
}