Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Analysis:
The key point is how to handle every digit.
1<=digit<=3
digit=4
digit =5
5<digit<=8
digit = 9
Java
public String intToRoman(int num) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
String[] symbol ={"I","V","X","L","C","D","M"};
String roman="";
int scale = 1000;
for(int i=6;i>=0;i-=2){
int digit = num/scale;
if(digit!=0){
if(digit<=3)
while((digit--)>0)
roman+=symbol[i];
else if(digit == 4){
roman+=symbol[i];
roman+=symbol[i+1];
}
else if(digit ==5)
roman+=symbol[i+1];
else if(digit <=8){
roman+=symbol[i+1];
while(((digit--)-5)>0)
roman+=symbol[i];
}
else if(digit ==9){
roman+=symbol[i];
roman+=symbol[i+2];
}
}
num = num%scale;
scale/=10;
}
return roman;
}
c++
string intToRoman(int num) {
char symbol[7] = {'I','V','X','L','C','D','M'};
string roman;
int scale = 1000;
for(int i=6;i>=0;i-=2){
int digit = num/scale;
if(digit!=0){
if(digit<=3){
roman.append(digit,symbol[i]);
}else if(digit == 4){
roman.append(1,symbol[i]);
roman.append(1,symbol[i+1]);
}else if(digit == 5){
roman.append(1,symbol[i+1]);
}else if(digit<=8){
roman.append(1,symbol[i+1]);
roman.append(digit-5,symbol[i]);
}else if(digit == 9){
roman.append(1,symbol[i]);
roman.append(1,symbol[i+2]);
}
}
num = num%scale;
scale /=10;
}
return roman;
}