12. Integer to Roman
题目描述
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 before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (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.
思路
仔细看一下其实三个字母对应一位十进制数字,比如I和V都是对应到个位上的数字,当然特殊的9是用IX来表示的。所以我们可以一位一位地分开处理整个十进制数。
首先取出个位数字x,然后判断跟x的大小,等于9就是IX
,等于5就是一个V
,大于5就在V
的右边添加x-5个I
,等于4就是IV
,小于4就x个I
x
=
{
I
X
if
x
=
9
V
I
.
.
.
I
⎵
x-5
if
9
>
x
>
5
V
if
x
=
5
I
V
if
x
=
4
I
.
.
.
I
⎵
x
if
x
<
4
x = \begin{cases} IX &\text{if } x = 9 \\ V \underbrace{I...I}_{\text{x-5}} &\text{if } 9 > x > 5 \\ V &\text{if } x = 5 \\ IV &\text{if } x = 4 \\ \underbrace{I...I}_{\text{x}} &\text{if } x < 4 \end{cases}
x=⎩⎪⎪⎪⎪⎪⎪⎪⎪⎨⎪⎪⎪⎪⎪⎪⎪⎪⎧IXVx-5
I...IVIVx
I...Iif x=9if 9>x>5if x=5if x=4if x<4
如果换到十位数字就是把上表中的X、V、I换成C、L、X
然后百位数字就是换成M、D、C
千位数字只到3,就是说只可能是x个M
代码
class Solution {
public:
string intToRoman(int num) {
// M, D, C, L, X, V, I
char c[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
int scale = 10;
string result;
for (int i = 0; i < 4; i++) {
int x = num % scale;
if (x == 9) {
result.append(1 ,c[2 * i + 2]);
result.append(1 ,c[2 * i]);
}
else if (x > 5) {
for (int j = 0; j < x - 5; j++) {
result.append(1 ,c[2 * i]);
}
result.append(1 ,c[2 * i + 1]);
} else if (x == 5) {
result.append(1 ,c[2 * i + 1]);
} else if (x == 4) {
result.append(1 ,c[2 * i + 1]);
result.append(1 ,c[2 * i]);
} else {
for (int j = 0; j < x; j++) {
result.append(1 ,c[2 * i]);
}
}
num /= scale;
}
reverse(result.begin(),result.end());
return result;
// return strrev(result);
}
};
Runtime: 40 ms, faster than 97.19% of C++ online submissions for Integer to Roman.