[LintCode] Integer to Roman 整数转化成罗马数字
Given an integer, convert it to a roman numeral.
The number is guaranteed to be within the range from 1
to 3999
.
Clarification
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]; } };