Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
没啥算法技术含量,搞明白Roman Integer的构造,按照千位,百位,十位和个位的数字来加一加就行了。
public class Solution {
public String intToRoman(int num) {
StringBuilder builder = new StringBuilder();
int thousand = num / 1000;
for(int i = 1; i <= thousand; i++){
builder.append("M");
}
int hundred = num % 1000 / 100;
//900
if(hundred == 9)
builder.append("CM");
//0~400
else if(hundred < 4){
for(int i = 1; i <= hundred; i++)
builder.append("C");
}
//400
else if(hundred == 4){
builder.append("CD");
}
//500~800
else{
builder.append("D");
for(int i = 6; i <= hundred; i++)
builder.append("C");
}
int tens = num % 100 / 10;
//90
if(tens == 9)
builder.append("XC");
//0~40
else if(tens < 4){
for(int i = 1; i <= tens; i++)
builder.append("X");
}
//40
else if(tens == 4){
builder.append("XL");
}
//50~80
else{
builder.append("L");
for(int i = 6; i <= tens; i++)
builder.append("X");
}
int ones = num % 10;
//9
if(ones == 9)
builder.append("IX");
//0~4
else if(ones < 4){
for(int i = 1; i <= ones; i++)
builder.append("I");
}
//4
else if(ones == 4){
builder.append("IV");
}
//5~8
else{
builder.append("V");
for(int i = 6; i <= ones; i++)
builder.append("I");
}
return builder.toString();
}
}