-
Notifications
You must be signed in to change notification settings - Fork 0
12. Integer to Roman
Jacky Zhang edited this page Aug 2, 2016
·
1 revision
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
String类题目
| I | V | X | L | C | D | M | | --- | --- | --- | --- | --- | --- | --- | --- | | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
这个题目的注意点是罗马数字4,9,40,90 ... 的写法有所不同,需要单独处理。
public class Solution {
public String intToRoman(int num) {
int[] intDict = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] romanDict = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int i = 0;
StringBuilder sb = new StringBuilder();
while(num > 0) {
if(num >= intDict[i]) {
sb.append(romanDict[i]);
num -= intDict[i];
} else {
i++;
}
}
return sb.toString();
}
}