【LeetCode】012. Integer to Roman

时间:2023-03-10 08:20:35
【LeetCode】012. Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

题解:

  观察 1 到 10 :Ⅰ,Ⅱ,Ⅲ,Ⅳ(IIII),Ⅴ,Ⅵ,Ⅶ,Ⅷ,Ⅸ,Ⅹ,Ⅺ

  难点在于出现字符不能连续超过三次,以及大数左边至多有一个小数。所以要分情况:1 - 3,4,5 - 8,9。将小数在大数左边的情况摘出来。

Solution 1

  贪心策略

 class Solution {
public:
string intToRoman(int num) {
string res = "";
vector<int> weights{, , , , , , , , , , , , };
vector<string> tokens{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; int i = ;
while (num && i < weights.size()) {
while (num >= weights[i]) {
num -= weights[i];
res += tokens[i];
}
++i;
} return res;
}
};

Solution 2

 class Solution {
public:
string intToRoman(int num) {
vector<string> M = { "", "M", "MM", "MMM" };
vector<string> C = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
vector<string> X = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
vector<string> I = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
return M[num / ] + C[(num % ) / ] + X[(num % ) / ] + I[num % ];
}
};