You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Example 1:
Input: 3
Output: "III"
Example 2:
Input: 4
Output: "IV"
Example 3:
Input: 9
Output: "IX"
Example 4:
Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Example 5:
Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= num <= 3999
之前那篇文章写的是罗马数字转化成整数 Roman to Integer, 这次变成了整数转化成罗马数字,基本算法还是一样。由于题目中限定了输入数字的范围 (1 - 3999), 使得题目变得简单了不少。
class Solution {
public:
string intToRoman(int num) {
string res = "";
vector<char> roman{'M', 'D', 'C', 'L', 'X', 'V', 'I'};
vector<int> value{1000, 500, 100, 50, 10, 5, 1};
for (int n = 0; n < 7; n += 2) {
int x = num / value[n];
if (x < 4) {
for (int i = 1; i <= x; ++i) res += roman[n];
} else if (x == 4) {
res = res + roman[n] + roman[n - 1];
} else if (x > 4 && x < 9) {
res += roman[n - 1];
for (int i = 6; i <= x; ++i) res += roman[n];
} else if (x == 9) {
res = res + roman[n] + roman[n - 2];
}
num %= value[n];
}
return res;
}
};
Activity
sonnyhcl commentedon Sep 29, 2019
首先感谢大佬把自己的题解和思路分享出来!刷题的莫大福音啊
这里的
基本字符部分的markdown列表似乎乱码了呢PS 为什么不把题解纳入git repo进行管理呢 还可以利用gitbook这种工具来生成电子书 要是大佬想做的话我可以帮忙一起搭建啊 之前做过一个类似的电子书项目参见https://github.com/xupsh/pp4fpgas-cn 和 https://xupsh.gitbook.io/pp4fpgas-cn/
grandyang commentedon Sep 29, 2019
哈哈,可以加个微信讨论一下,关注微信公众号然后留下你的微信哈。
(搜索【shua2sum】或扫描二维码关注微信公众号【刷尽天下】)