Given an integer, convert it to a roman numeral.
The number is guaranteed to be within the range from 1
to 3999
.
Have you met this question in a real interview?
Clarification
What is Roman Numeral?
- https://en.wikipedia.org/wiki/Roman_numerals
- https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
- http://baike.baidu.com/view/42061.htm
Example
4
-> IV
12
-> XII
21
-> XXI
99
-> XCIX
more examples at: http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
LeetCode上的原题,请参见我之前的博客Integer to Roman。
解法一:
class Solution { public: /** * @param n The integer * @return Roman representation */ string intToRoman(int n) { string res = ""; vector<vector<string>> v {{"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"}}; int cnt = 1000; for (int i = 3; i >= 0; --i) { int t = n / cnt; if (t) res += v[i][t - 1]; n %= cnt; cnt /= 10; } return res; } };
解法二:
class Solution { public: /** * @param n The integer * @return Roman representation */ string intToRoman(int n) { string res = ""; vector<int> val {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; vector<string> str{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; for (int i = 0; i < val.size(); ++i) { while (n >= val[i]) { n -= val[i]; res += str[i]; } } return res; } };
解法三:
class Solution { public: /** * @param n The integer * @return Roman representation */ string intToRoman(int n) { string res = ""; vector<string> v1 {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; vector<string> v2 {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; vector<string> v3 {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; vector<string> v4 {"", "M", "MM", "MMM"}; return v4[n / 1000] + v3[(n % 1000) / 100] + v2[(n % 100) / 10] + v1[n % 10]; } };
时间: 2024-10-10 09:02:54