
Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
逐区间做处理。
解法一:非递归
class Solution {
public:
string intToRoman(int num) {
string ret;
//M<-->1000
while(num >= )
{
ret += 'M';
num -= ;
}
//to here, num < 1000
//CM<-->900
if(num >= )
{
ret += "CM";
num -= ;
}
//to here, num < 900
//D<-->500
if(num >= )
{
ret += 'D';
num -= ;
}
//to here, num < 500
if(num >= )
{
ret += "CD";
num -= ;
}
//to here, num < 400
//C<-->100
while(num >= )
{
ret += 'C';
num -= ;
}
//to here, num < 100
//XC<-->90
if(num >= )
{
ret += "XC";
num -= ;
}
//to here, num < 90
//L<-->50
if(num >= )
{
ret += 'L';
num -= ;
}
//to here, num < 50
//XL<-->40
if(num >= )
{
ret += "XL";
num -= ;
}
//to here, num < 40
//X<-->10
while(num >= )
{
ret += 'X';
num -= ;
}
//to here, num < 10
//IX<-->9
if(num >= )
{
ret += "IX";
num -= ;
}
//to here, num < 9
//V<-->5
if(num >= )
{
ret += 'V';
num -= ;
}
//to here, num < 5
//IV<-->4
if(num >= )
{
ret += "IV";
num -= ;
}
//to here, num < 4
//I<-->1
while(num >= )
{
ret += 'I';
num -= ;
}
return ret;
}
};
解法二:递归
class Solution {
public:
string intToRoman(int num) {
if(num >= )
return "M" + intToRoman(num-);
else if(num >= )
return "CM" + intToRoman(num-);
else if(num >= )
return "D" + intToRoman(num-);
else if(num >= )
return "CD" + intToRoman(num-);
else if(num >= )
return "C" + intToRoman(num-);
else if(num >= )
return "XC" + intToRoman(num-);
else if(num >= )
return "L" + intToRoman(num-);
else if(num >= )
return "XL" + intToRoman(num-);
else if(num >= )
return "X" + intToRoman(num-);
else if(num >= )
return "IX" + intToRoman(num-);
else if(num >= )
return "V" + intToRoman(num-);
else if(num >= )
return "IV" + intToRoman(num-);
else if(num >= )
return "I" + intToRoman(num-);
else
return "";
}
};