题目:Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
在解题之前,最好要先了解一下罗马数字组合原理
罗马数字:
罗马数字采用 7 个罗马字母作数字,即 I(1),V(5),X(10),L(50),C(100),D(500),M(1000);相同的数字连写,所表示的数等于这些数字相加得到的数,如 III = 3,XX = 20, CC = 200, MM = 2000;小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 VIII = 8, XII = 12;为了简洁性,比如我们想要表达 80, 我们应该选择 LXXX, 而不是 8 个 X 连在一起; 小的数字(仅限于 I, X, C) 在大的数字的左边,所表示的数等于大数减小数得到的数。这样的组合共有 6 个,分别是 IV(4), IX(9), XL(40), XC(90), CD(400), CM(900),这 6 个 数字的表示不能应用上面的加法准则若还不能理解,可以对照该网页https://zhidao.baidu.com/question/198335199.html 列出的罗马数字。
解题代码一如下,从整数的最低位即个位开始处理整数,代码比较繁琐,但理解起来比较容易
class Solution {public: string intToRoman(int num) { const char symbol[4][2] = {{'I', 'V'}, {'X', 'L'}, {'C', 'D'}, {'M'}}; string roman; for (int bit = 0; num; ++bit, num /= 10) { int tmp = num < 10 ? num : num % 10; string s; if (tmp == 9) { s.push_back(symbol[bit][0]); s.push_back(symbol[bit + 1][0]); } else if (5 <= tmp && tmp < 9) { s.push_back(symbol[bit][1]); for (int i = tmp - 5; i > 5; --i) s.push_back(symbol[bit][0]); } else if (tmp == 4) { s.push_back(symbol[bit][0]); s.push_back(symbol[bit][1]); } else { for (int i = tmp; i >= 1; --i) s.push_back(symbol[bit][0]); } roman = s + roman; } return roman; }};解题代码二,从整数的最高位开始处理,代码很简洁,该代码参考了网址https://github.com/soulmachine/leetcode#leetcode题解题目题目
class Solution {public: string intToRoman(int num) { const int radix[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; const string symbol[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; string roman; for (int i = 0; num; ++i) { int counts = num / radix[i]; num %= radix[i]; for ( ; counts > 0; --counts) roman += symbol[i]; } return roman; }};新闻热点
疑难解答