您的位置:首页 > 其它

【LeetCode】13. Roman to Integer && 12. Integer to Roman

2016-03-09 09:56 337 查看
Given a roman numeral, convert it to an integer.

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

[罗马转整数]

/*
1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};

100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};

1000~3000: {"M", "MM", "MMM"}.
*/
class Solution {
public:
int toNum(char c)
{
switch(c){
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
}
return 0;
}
int romanToInt(string s) {
int result = toNum(s[0]);
int i;
for(i=1; i < s.length(); i++)
{
if(toNum(s[i])<=toNum(s[i-1])){
result +=toNum(s[i]) ;
}
else if(toNum(s[i])>toNum(s[i-1]))
{
result +=toNum(s[i]) - 2*toNum(s[i-1]);
}
}
return result;
}
};


Given an integer, convert it to a roman numeral.

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

【整数转罗马】
class Solution {
public:
string intToRoman(int num) {
string s="";
string roman[4][10]={{"","I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"","C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"","M", "MM", "MMM"}
};
int position = 0;
while(0 < num)
{
s = roman[position][num%10] + s;
position++;
num = num / 10;
}
return s;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: