Problem:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
把阿拉伯数字转换为罗马数字输出。百度一下对应的 I V X L C D M,代表1,5,10,50,100,500,1000 然后写一个子函数,输入数字和相应的位数级别,如个位为level 1,千为4.因为最多不会超过四千。所以可以如下。注意了,string用法很好,直接加就可以。
class Solution {
private:
string corRoman(int val, int level)
{
string base, media, large;
string s = "";
if (level == ) // 个位
{
base = "I";
media = "V";
large = "X";
}
else if (level == )
{
base = "X";
media = "L";
large = "C";
}
else if (level == )
{
base = "C";
media = "D";
large = "M";
}
else
{
base = "M";
}
if (val == )
return "";
if( val < )
{
for ( int i = ; i < val; i++)
s += base;
return s;
}
if (val == )
{
return base + media;
}
if (val < )
{
s = media;
for (int i = ; i < val; i++)
s+=base;
return s;
}
return base + large;
}
public:
string intToRoman(int num)
{
string s;
int a;
for (int i = ; i > ; i-- )
{
a = num/pow(,i - );
num %= (int)pow(, i - );
s+=corRoman(a,i);
}
return s;
}
};
这样就Accept了。