1 题目
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II
in Roman numeral, just two one's added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven is written as XXVII
, which is XX
+ V
+ II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
2 尝试解
class Solution {
public:
string intToRoman(int num) {
map<int,char> index ={{1,'I'},{5,'V'},{10,'X'},{50,'L'},{100,'C'},{500,'D'},{1000,'M'}};
string result = "";
int deci = 1;
while(num){
if(num % 5 != 4){ //neither 4 nor 9
result = result.insert(0,num%5,index[deci]);
result = result.insert(0,(num%10)/5,index[5*deci]); //if no less than 5
}
else if(num % 10 == 4){
result = result.insert(0,1,index[5*deci]);
result = result.insert(0,1,index[deci]);
}
else{
result = result.insert(0,1,index[10*deci]);
result = result.insert(0,1,index[deci]);
}
num = num / 10;
deci = deci * 10;
}
return result;
}
};
3 标准解
class Solution {
public:
const static string THOUS[];
const static string HUNDS[];
const static string TENS[];
const static string ONES[];
string intToRoman(int num) {
string result;
result += THOUS[(int)(num/1000)%10];
result += HUNDS[(int)(num/100)%10];
result += TENS[(int)(num/10)%10];
result += ONES[num%10];
return result;
}
};
const string Solution::THOUS[] = {"","M","MM","MMM"};
const string Solution::HUNDS[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
const string Solution::TENS[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
const string Solution::ONES[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};