Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解析:首先要清楚罗马数字的组成:
基本字符:
I、V、X、L、C、D、M
int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] roms = {“M”, “CM”, “D”, “CD”, “C”, “XC”, “L”, “XL”, “X”, “IX”, “V”, “IV”, “I”};
public class Solution {
public String intToRoman(int num) {
int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] roms = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
String res = "";
int loc = 0;
while (num > 0) {
if (num >= nums[loc]) {
num -= nums[loc];
res += roms[loc];
}
else {
loc ++;
}
}
return res;
}
}