Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
The meaning of the original text is very simple, that is to convert the input integer variables into Roman numerals for output. The conversion relationship between integer variables and Roman numerals is as follows:
, , , , , ,
E.g:2341 -> MMCCCXLI
3021 -> MMMXXI
C ++ (2ms) :
class Solution {
public:
string intToRoman(int num) {
stringstream res;
char roman_numeral[] = {'M','D','C','L','X','V','I'};
int integer[] = {1000,500,100,50,10,5,1};
vector<pair<int,char>> integerToroman;
for(int i=0; i<7; ++i){
integerToroman.push_back(make_pair(integer[i],roman_numeral[i]));
}
int stage;
for(int j=0;j<7;j+=2)
{
if(float(num)/float(integer[j]) >= 1){
stage=j;
cout<<num<<endl;
cout<<stage<<endl;
break;
}
}
for(int j=stage; j<integerToroman.size(); j+=2)
{
int result = num/integerToroman[j].first;
if(result<4){
for(int i=0;i<result;i++){
res << integerToroman[j].second;
}
}
if(result==4){
res << integerToroman[j].second << integerToroman[j-1].second;
}
if(result>4 && result<9){
res << integerToroman[j-1].second;
for(int k=5;k<result; k++){
res << integerToroman[j].second;
}
}
if(result==9){
res << integerToroman[j].second << integerToroman[j-2].second;
}
num = num % integerToroman[j].first;
}
return (res.str());
}
};
Python (30ms)
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
roman_numeral=['M','D','C','L','X','V','I']
integer=[1000,500,100,50,10,5,1]
stage=0
res=""
for i in range(len(integer),2):
if float(num)/float(integer[i]) >=1:
stage=i
break
for j in range(stage,len(integer),2):
result=num/integer[j]
if result<4:
for k in range(result):
res = res + roman_numeral[j]
elif result ==4:
res = res + roman_numeral[j]+ roman_numeral[j-1]
elif result > 4 and result < 9:
res = res + roman_numeral[j-1]
for z in range(5,result):
res = res + roman_numeral[j]
elif result==9:
res = res + roman_numeral[j] + roman_numeral[j-2]
num = num % integer[j]
return res