Description
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Solution
- 大->小满减
设置关键数值及对应字符的map,从大到小遍历,满则减,由于map是按key由小及大排序,因此用rbegin()->rend()保证按key由大及小的遍历顺序
string intToRoman(int num) {
map<int, string> myMap = {{1000, "M"},{900, "CM"},{500, "D"},{400, "CD"},{100, "C"},{90, "XC"},{50, "L"},{40, "XL"},{10, "X"},{9, "IX"},{5, "V"},{4, "IV"},{1, "I"}};
string ret = "";
for (auto it = myMap.rbegin(); it != myMap.rend(); ++it) {
while (num >= it->first) {
ret += it->second;
num -= it->first;
}
}
return ret;
}
- 暴力映射
一个<3999的整数,直接求千百十个位的数值,对应映射到对应的string
string intToRoman(int num) {
vector<string> thousands{"", "M", "MM", "MMM"};
vector<string> hundreds{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
vector<string> tens{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
vector<string> digits{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return thousands[num/1000] + hundreds[(num%1000)/100] + tens[(num%100)/10] + digits[num%10];
}