12. Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
class Solution {
public:
string intToRoman(int num) {
}
};
解题思路:
题目背景解析:
罗马数字共有
7
个,即
I(1)
,
V(5)
,
X(10)
,
L(50)
,
C(100)
,
D(500)
,
M(1000)
。
具体
roman
数字表示如下
I
|
V
|
X
|
L
|
C
|
D
|
M
|
1
|
5
|
10
|
50
|
100
|
500
|
1000
|
7
个字母分别代表不同的数字,用这
7
个字母排列组成可以组成所有的整数。
简单规则如下:
1
、相同的字母或者小的字母在大字母前就是相加。
III = 3 IV =6 ;
2
、大的字母在小的字母前面就是想减。
VI = 4 CM = 900;
-
自己的解题思路
使用了辅助数组进行求解。当然这个辅助数组具有一定的特征,可以使用函数进行求解。然而,我们一般还是用空间来换时间。
这里使用了一个特征,就是
789
——对应罗马数字的(
7
【百位】
+8
【十位】
+9
【个位】)。
-
别人的解题思路
与我的类似,但是对于
1
,
4
,
5
,
9
分开讨论,可以借鉴一下。
学习收获:
-
对于 stack, 没有 push_back(), 只有 push() ; 这个容易思维定势,需要注意。
其实,现在感觉
stack
还是很好用的。
-
Word 技巧
对于参考文献,经常出现中文拉的很长,就像“参
考
文
献”,然后英文往后排的现象,可以通过以下方法进行解决。
选中英文,右键
->
段落
->
中文版式
,
在“允许西文在单词中间换行”打勾。
附件
1
:程序
1
、自己的程序:
string
str
[
4
][
10
]
=
{
{
""
,
"I"
,
"II"
,
"III"
,
"IV"
,
"V"
,
"VI"
,
"VII"
,
"VIII"
,
"IX"
},
{
""
,
"X"
,
"XX"
,
"XXX"
,
"XL"
,
"L"
,
"LX"
,
"LXX"
,
"LXXX"
,
"XC"
},
{
""
,
"C"
,
"CC"
,
"CCC"
,
"CD"
,
"D"
,
"DC"
,
"DCC"
,
"DCCC"
,
"CM"
},
{
""
,
"M"
,
"MM"
,
"MMM"
}
};
class
Solution
{
public
:
string
intToRoman
(
int
num
)
{
if
(
num
<=
0
||
num
>
3999
)
return
string
();
string
res
;
res
.
reserve
(
200
);
stack
<
int
>
st
;
int
digits
=
0
;
while
(
num
)
{
st
.
push
(
num
%
10
);
num
/=
10
;
++
digits
;
}
while
(!
st
.
empty
())
{
int
temp
=
st
.
top
();
res
+=
str
[--
digits
][
temp
];
st
.
pop
();
}
return
res
;
}
};
2
、别人的程序
class
Solution
{
public
:
string
intToRoman
(
int
num
)
{
string
res
;
string
sym
[]
=
{
"M"
,
"CM"
,
"D"
,
"CD"
,
"C"
,
"XC"
,
"L"
,
"XL"
,
"X"
,
"IX"
,
"V"
,
"IV"
,
"I"
};
int
val
[]
=
{
1000
,
900
,
500
,
400
,
100
,
90
,
50
,
40
,
10
,
9
,
5
,
4
,
1
};
for
(
int
i
=
0
;
num
!=
0
;
i
++)
{
while
(
num
>=
val
[
i
])
{
num
-=
val
[
i
];
res
+=
sym
[
i
];
}
}
return
res
;
}
};
附件2:扩展阅读:
参考资料:
-
https://github.com/githubwoniu/learnprogram/blob/master/leetcode/13/leetcode_13.md