class Solution {
public:
string intToRoman(int num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
char symbol[9] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
string res = "";
int scale = 1000;
for (int i = 6; i >= 0; i -= 2)
{
int digit = num / scale;
appendNumToRoman(digit, res, symbol + i);
num %= scale;
scale /= 10;
}
return res;
}
void appendNumToRoman(int num, string& roman, char symbols[])
{
if (num == 0)
return;
if (num <= 3)
roman.append(num, symbols[0]);
else if (num == 4)
{
roman.append(1, symbols[0]);
roman.append(1, symbols[1]);
}
else if (num <= 8)
{
roman.append(1, symbols[1]);
roman.append(num - 5, symbols[0]);
}
else
{
roman.append(1, symbols[0]);
roman.append(1, symbols[2]);
}
}
};[Leetcode] Integer to Roman
最新推荐文章于 2020-06-29 15:21:54 发布
本文详细介绍了使用C++实现罗马数字转换的算法过程,包括符号映射、位数处理和进位逻辑,旨在帮助开发者理解并实现复杂的数字转换功能。
624

被折叠的 条评论
为什么被折叠?



