您的位置:首页 > 其它

LintCode笔记(5)——整数转罗马数字

2016-07-26 08:54 274 查看
给定一个整数,将其转换成罗马数字。
返回的结果要求在1-3999的范围内。

您在真实的面试中是否遇到过这个题?

Yes

说明

什么是 罗马数字?

https://en.wikipedia.org/wiki/Roman_numerals
https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
http://baike.baidu.com/view/42061.htm

样例

4
->
IV

12
->
XII

21
->
XXI

99
->
XCIX

更多案例,请戳http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm

class Solution {
public:
/**
* @param n The integer
* @return Roman representation
*/
string intToRoman(int n) {
// Write your code here
int thousand = n/1000;
int hundrad = (n - thousand*1000)/100;
int ten = (n-thousand*1000-hundrad*100)/10;
int one = n-thousand*1000-hundrad*100-ten*10;
string result;
string sThousand(thousand,'M');
result += sThousand;
if(hundrad <= 3)
{
string sHundrad(hundrad,'C');
result += sHundrad;
}
else if(hundrad == 4)
{
string sHundrad("CD");
result += sHundrad;
}
else if(hundrad == 5)
{
string sHundrad("D");
result += sHundrad;
}
else if(hundrad >=6 && hundrad <= 8)
{
string sHundrad = "D";
string tmp(hundrad-5,'C');
sHundrad += tmp;
result += sHundrad;
}
else
{
string sHundrad = "CM";
result += sHundrad;
}
//ten
if(ten <= 3)
{
string sTen(ten,'X');
result += sTen;
}
else if(ten == 4)
{
string sTen("XL");
result += sTen;
}
else if(ten == 5)
{
string sTen("L");
result += sTen;
}
else if(ten >=6 && ten <= 8)
{
string sTen = "L";
string tmp(ten-5,'X');
sTen += tmp;
result += sTen;
}
else
{
string sTen = "XC";
result += sTen;
}
//one
if(one <= 3)
{
string sOne(one,'I');
result += sOne;
}
else if(one == 4)
{
string sOne("IV");
result += sOne;
}
else if(one == 5)
{
string sOne("V");
result += sOne;
}
else if(one >=6 && one <= 8)
{
string sOne = "V";
string tmp(one-5,'I');
sOne += tmp;
result += sOne;
}
else
{
string sOne = "IX";
result += sOne;
}
return result;
}
};


代码的主要思路是把整型数的各位分别求出来,然后根据罗马数字的语法分情况讨论。代码的思路比较浅显,很容易懂,但是代码比较冗余,不是很好。这里用到了一个不太常用的string类型对象的初始化方法,即:

//这里n是int类型,c是char类型,意思是用n个c来初始化字符串s
string s(n,c);


下面有人用Java写的比较好的代码,如下所示:

public class Solution {
/**
* @param n The integer
* @return Roman representation
*/
public String intToRoman(int n) {
// Write your code here
int[] numbers = { 1000,  900,  500,  400,  100,   90,  50,   40,   10,    9,    5,    4, 1 };

String[] letters = { "M",  "CM",  "D",  "CD", "C",  "XC", "L",  "XL",  "X",  "IX", "V",  "IV", "I" };
String res ="" ;
for(int i = 0;i<13;i++){
if(n >= numbers[i]){
int count = n/numbers[i];
n = n%numbers[i];
for(int j=0;j<count ;j++){
res= res + letters[i];
}
}
}
return res;
}
};
上面的代码的思路就是把各个区分点分别表示出来,然后求这些区分点处的数字的个数,即为结果。

罗马数字转整形数字的方法,见我这篇博客LintCode笔记(2)——罗马数字转整型数字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: