LeetCode 12 - 整数转罗马数字 - [简单模拟]

时间:2021-12-14 17:19:25

题目链接:https://leetcode-cn.com/problems/integer-to-roman/

题解:

把 $1,4,5,9,10,40,50, \cdots, 900, 1000$ 均看做档位,优先转化大的档位,直到不能转化为止,然后降一个档位,继续转化,反复如此直到 $num=0$。

AC代码:

struct Solution
{
int o[]={,,,,,,,,,,,,};
string mp[];
Solution()
{
mp[]="I", mp[]="IV", mp[]="V", mp[]="IX";
mp[]="X", mp[]="XL", mp[]="L", mp[]="XC";
mp[]="C", mp[]="CD", mp[]="D", mp[]="CM", mp[]="M";
}
string intToRoman(int num)
{
string res;
int p=;
while(num>)
{
while(num<o[p]) p--;
while(num>=o[p])
{
num-=o[p];
res+=mp[p];
}
}
return res;
}
};