Integer to Roman
Total Accepted: 31922 Total Submissions: 91429My Submissions
Question Solution
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Show Tags
Have you met this question in a real interview?
Yes
No
【题目】
Given a roman numeral, convert it to an integer. Or, Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
【罗马数字】
1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
1000~3000: {"M", "MM", "MMM"}.
public class Solution {
public String intToRoman(int num) {
String[][] roman = {
{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"", "M", "MM", "MMM"}
};
String ret = "";
int digit = 0;
while (num != 0) {
int remain = num % 10;
ret = roman[digit][remain] + ret;
digit++;
num /= 10;
}
return ret;
}
}