目录
- 12. 整数转罗马数字
- 13. 罗马数字转整数
12. 整数转罗马数字
难度:中等
使用贪心的思想。
正确解法:
class Solution {
public:
string intToRoman(int num) {
string s = "";
vector<string> str_list = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
vector<int> int_list = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
int n = int_list.size();
int k = 0, m = num;
for(int i = 0; i < n; i++){
k = m / int_list[i];
m = m % int_list[i];
if(k != 0){
for(int j = 0; j < k; j++)s += str_list[i];
}
}
return s;
}
};
13. 罗马数字转整数
正确解法:
class Solution {
public:
int romanToInt(string s) {
map<char, int> dic;
dic['I'] = 1;
dic['V'] = 5;
dic['X'] = 10;
dic['L'] = 50;
dic['C'] = 100;
dic['D'] = 500;
dic['M'] = 1000;
int n = s.length();
int ans = dic[s[0]];
int last_num = ans;
for(int i = 1; i < n; ++i){
int now = dic[s[i]];
ans += now;
if(last_num < now){
ans -= 2 * last_num;
}
last_num = now;
}
return ans;
}
};
结果: