Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
本题要明确罗马数字的规则,如果当前比前一个大,说明这一段的值应该是当前这个值减去上一个值。比如 IV = 5 – 1;否 则,将当前值加入到结果中,然后开始下一段记录。比如 VI = 5 + 1, II=1+1
class Solution {
public:
inline int map(const 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;
default:return 0;
}
}
int romanToInt(string s) {
int first,next;
int result=0;
for(int i=0;i<s.size();i++)
{
if(i>0&&map(s[i])>map(s[i-1]))
{
result += (map(s[i])-2*map(s[i - 1]));
}
else
{
result +=map(s[i]);
}
}
return result;
}
};
Integer to Roman
Given an integer, convert it to a roman numeral.
我首先想到的是一个比较死板的方法,就是穷举,方法也被leetcode接受了。。如下:
class Solution {
public:
string intToRoman(int num) {
int A[7]={0};
A[0]=num/1000;
num=num%1000;
A[1]=num/500;
num=num%500;
A[2]=num/100;
num=num%100;
A[3]=num/50;
num=num%50;
A[4]=num/10;
num=num%10;
A[5]=num/5;
num=num%5;
A[6]=num;
string result;
for(int i=0;i<A[0];i++)
{
result.push_back('M');
}
if(A[1]==1 && A[2]==4)
{
result.push_back('C');
result.push_back('M');
}
else if(A[1]==0 && A[2]==4)
{
result.push_back('C');
result.push_back('D');
}
else
{
for(int i=0;i<A[1];i++)
{
result.push_back('D');
}
for(int i=0;i<A[2];i++)
{
result.push_back('C');
}
}
if(A[3]==1 && A[4]==4)
{
result.push_back('X');
result.push_back('C');
}
else if(A[3]==0 && A[4]==4)
{
result.push_back('X');
result.push_back('L');
}
else
{
for(int i=0;i<A[3];i++)
{
result.push_back('L');
}
for(int i=0;i<A[4];i++)
{
result.push_back('X');
}
}
if(A[5]==1 && A[6]==4)
{
result.push_back('I');
result.push_back('X');
}
else if(A[5]==0 && A[6]==4)
{
result.push_back('I');
result.push_back('V');
}
else
{
for(int i=0;i<A[5];i++)
{
result.push_back('V');
}
for(int i=0;i<A[6];i++)
{
result.push_back('I');
}
}
return result;
}
};
看到一个比较好的方法,建立了字符串,如下:
string intToRoman(int num) {
string table[] = {"M", "CM","D","CD","C","XC","L","XL","X","IX","V","IV"
,"I"};
int values[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
string result;
for(int iter = 0; iter < 13;)
{
if(num >= values[iter])
{
result += table[iter];
num -= values[iter];
}
else
++iter;
}
return result;
}