Given an integer, convert it to a roman numeral.
The number is guaranteed to be within the range from 1
to 3999
.
分析:前提先掌握罗马数字规律。我们将3999一下可能代表数字的所有罗马字母放入数组,从高到低依次去除n。注意900,400,90,40,9,4由于涉及到变位,为了简化算法,直接将这几个数字对应的字母也放入数组。
public class Solution {
/**
* @param n The integer
* @return Roman representation
*/
public String intToRoman(int n) {
// I 1
// V 5
// X 10
// L 50
// C 100
// D 500
// M 1000
int[] numbers = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] letters = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
String result ="";
for(int i = 0; i < 13; i++){
if(n >= numbers[i]){
int count = n / numbers[i];
n = n % numbers[i];
for(int j = 0; j < count; j++){
result += letters[i];
}
}
}
return result;
}
}