【LeetCode 面试经典150题】12. Integer to Roman 整数转罗马数字
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, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 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.
中文释义
罗马数字由七个不同的符号表示:I、V、X、L、C、D和M。
符号 | 数值 |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
例如,数字2用罗马数字表示为II,即两个1相加。数字12用XII表示,即X + II。数字27用XXVII表示,即XX + V + II。
罗马数字通常从左到右书写,且大的符号在前,小的符号在后。然而,数字4的表示并不是IIII。相反,数字4用IV表示。因为1在5的前面,所以我们要减去它,得到4。同样的原则适用于数字9,它表示为IX。总共有六种情况需要使用减法规则:
- I可以放在V(5)和X(10)的前面,得到4和9。
- X可以放在L(50)和C(100)的前面,得到40和90。
- C可以放在D(500)和M(1000)的前面,得到400和900。
给定一个整数,将其转换成罗马数字。
Example 1:
Input: num = 3
Output: “III”
Explanation: 3 is represented as 3 ones.
Example 2:
Input: num = 58
Output: “LVIII”
Explanation: L = 50, V = 5, III = 3.
Example 3:
Input: num = 1994
Output: “MCMXCIV”
Explanation: M = 1000, CM = 900, XC = 90, and IV = 4.
Constraints:
1 <= num <= 3999
解题思路
要将整数转换为罗马数字,可以使用贪心算法的思想,从最大的罗马数字开始逐步减去,直到整数为0为止。
-
首先,定义两个数组
values
和reps
,分别存储罗马数字的整数值和对应的罗马字符。 -
创建一个空字符串
res
用于存储最终的罗马数字表示。 -
使用循环遍历
values
和reps
数组,从最大的罗马数字开始向最小的罗马数字遍历。 -
在每次循环中,检查当前整数
num
是否大于或等于values[i]
,如果是,就将values[i]
从num
中减去,并将对应的罗马字符reps[i]
添加到结果字符串res
中。 -
重复步骤4,直到
num
变为0。 -
返回结果字符串
res
作为整数对应的罗马数字表示。
这个算法的关键思想是尽可能多地使用大的罗马数字来表示整数,以得到最简洁的罗马数字表示。
class Solution {
public:
string intToRoman(int num) {
int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string reps[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
string res;
for(int i = 0; i < 13; i++) {
while(num >= values[i]) {
num -= values[i];
res += reps[i];
}
}
return res;
}
};