您的位置:首页 > 其它

leetcode012:Integer to Roman

2015-04-09 22:06 393 查看

问题描述

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

问题分析

阿拉伯数字转罗马数字,只要了解了规则(请看参考链接,解释的很清晰),代码还是很简单的。范围是1到3999,所以千位单独处理,而个十百位的处理逻辑完全一致:0123、4、5678、9四类情况。

代码

class Solution {
public:
string intToRoman(int num) {
string ans;
int q = num / 1000;//千位
for (int i = 0; i < q; i++){
ans += 'M';
}
q = num / 100 % 10;//百位
if (q == 9) ans += "CM";
else if (q >= 5){
ans += 'D';
for (int i = 0; i < q - 5; i++)
ans += 'C';
}
else if (q == 4)
ans += "CD";
else
{
for (int i = 0; i < q; i++)
ans += 'C';
}
q = num / 10 % 10;//十位
if (q == 9) ans += "XC";
else if (q >= 5){
ans += 'L';
for (int i = 0; i < q - 5; i++)
ans += 'X';
}
else if (q == 4)
ans += "XL";
else
{
for (int i = 0; i < q; i++)
ans += 'X';
}
q = num % 10;//个位
if (q == 9) ans += "IX";
else if (q >= 5){
ans += 'V';
for (int i = 0; i < q - 5; i++)
ans += 'I';
}
else if (q == 4)
ans += "IV";
else
{
for (int i = 0; i < q; i++)
ans += 'I';
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: