題目連結,此題跟
LintCode: Roman to Integer 羅馬數字轉成十進制整數剛好相反,直接用查表法解:
class Solution {
public:
string intToRoman(int num) {
if( num == 0 )
return "0";
string romanSymbol[4][10] = {
{"0", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"0", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"0", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"0", "M", "MM", "MMM"}
};
int romanValue[4] = { 1, 10, 100, 1000 };
string romanStr;
int tmpN = num;
int digit = 3;
int idx;
while(tmpN > 0) {
idx = tmpN / romanValue[digit];
if(idx > 0)
romanStr += romanSymbol[digit][idx];
tmpN = tmpN % romanValue[digit];
digit--;
}
return romanStr;
}
};
若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。
留言