問題描述:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
將數字轉換爲羅馬數字表示。
解題思路:
按照羅馬數字組數標準組合即可,附羅馬數字百度百科:http://baike.baidu.com/link?url=UUF_EffApqqZ3Hh2K_7f8NOYpFYIAtk8oWQMWkmN1KnO3TOeiitCwubqKI_boYSlsKOEij4zrwMT0oGN4Ev0YK
class Solution
{
public:
string intToRoman(int num)
{
map<int, char> Int_Roman;
Int_Roman.insert(pair<int,char>(1,'I'));
Int_Roman.insert(pair<int,char>(5,'V'));
Int_Roman.insert(pair<int,char>(10,'X'));
Int_Roman.insert(pair<int,char>(50,'L'));
Int_Roman.insert(pair<int,char>(100,'C'));
Int_Roman.insert(pair<int,char>(500,'D'));
Int_Roman.insert(pair<int,char>(1000,'M'));
string result;
if(num<0 || num >3999)
return "";
//確定個十百千位,他們相加起來正好等於num
int single = num % 10;
int ten = num % 100 - single;
int hundred = num % 1000 - num % 100;
int thousand = num - num % 100;
//確定千位
for(int j=0; j<thousand/1000; j++ )
{
result += Int_Roman[1000];
}
//確定百位
if(hundred == 900)
{
result += "CM";
}
else if(hundred == 400)
{
result += "CD";
}
else if(hundred < 400)
{
for(int j=0; j<hundred/100; j++ )
{
result += Int_Roman[100];
}
}
else
{
result += 'D';
for(int j=0; j<(hundred - 500)/100; j++ )
{
result += Int_Roman[100];
}
}
//確定十位
if(ten == 90)
{
result += "XC";
}
else if(ten == 40)
{
result += "XL";
}
else if(ten < 40)
{
for(int j=0; j<ten/10; j++ )
{
result += Int_Roman[10];
}
}
else
{
result += 'L';
for(int j=0; j<(ten - 50)/10; j++ )
{
result += Int_Roman[10];
}
}
//確定個位
if(single == 9)
{
result += "IX";
}
else if(single == 4)
{
result += "IV";
}
else if(single < 4)
{
for(int j=0; j<single/1; j++ )
{
result += Int_Roman[1];
}
}
else
{
result += 'V';
for(int j=0; j<(single - 5)/1; j++ )
{
result += Int_Roman[1];
}
}
//.....................................................
return result;
}
};