罗马数字转成阿拉伯数字,这里面需要知道罗马数字的构成规则。罗马数字通过7个不同字母的重复或组合,能够表示出所有正整数(罗马数字中没有0)。
- I = 1
- V = 5
- X = 10
- L = 50
- C = 100
- D = 500
- M = 1000
比如:IV表示4,VI表示6,XIX表示19,XXI表示21。
可以找到规律,如果左边的字母表示的数字小于右边的字母,则用右边的数字减去左边的数字;反之,则需要进行加法。
这两个不难,主要是找规律。
12. Integer to Roman
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)
{
vector<int> m1;
string result = "";
while (num/10 != 0)
{
m1.push_back(num % 10);
num /= 10;
}
m1.push_back(num);
for(int i = m1.size() - 1; i >= 0; i--)
{
if(i == 3)
{
for(int j = 1; j <= m1[i]; j++)
result += 'M';
}
else if(i == 2)
{
if(m1[i] == 9)
result += "CM";
else if (m1[i] == 4)
result += "CD";
else if(m1[i] >= 5 && m1[i] < 9)
{
result += "D";
for (int k = 0; k < m1[i] - 5; k++)
{
result += 'C';
}
}
else
{
for (int k = 0; k < m1[i]; k++)
{
result += 'C';
}
}
}
else if(i == 1)
{
if(m1[i]==9)
result += "XC";
else if(m1[i]==4)
result += "XL";
else if(m1[i]>=5 && m1[i]<9)
{
result += "L";
for(int k=0;k<m1[i]-5;k++)
{
result += 'X';
}
}
else
{
for(int k=0;k<m1[i];k++)
{
result += 'X';
}
}
}
else
{
if(m1[i]==9)
result += "IX";
else if(m1[i]==4)
result += "IV";
else if(m1[i]>=5 && m1[i]<9)
{
result += "V";
for(int k=0;k<m1[i]-5;k++)
{
result += 'I';
}
}
else
{
for(int k=0;k<m1[i];k++)
{
result += 'I';
}
}
}
}
return result;
}
};
13. Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution {
public:
int romanToInt(string s)
{
int result=0;
for(int i=s.size()-1;i>=0;i--)
{
if(s[i]=='I')
{
result+=1;
}
else if(s[i]=='V')
{
if(s[i-1]=='I' && i-1>=0)
{ result+=4;
i--;
}
else
result+=5;
}
else if(s[i]=='X')
{
if(s[i-1]=='I' && i-1>=0)
{ result+=9;
i--;
}
else
result+=10;
}
else if(s[i]=='L')
{
if(s[i-1]=='X' && i-1>=0)
{ result+=40;
i--;
}
else
result+=50;
}
else if(s[i]=='C')
{
if(s[i-1]=='X' && i-1>=0)
{ result+=90;
i--;
}
else
result+=100;
}
else if(s[i]=='D')
{
if(s[i-1]=='C' && i-1>=0)
{ result+=400;
i--;
}
else
result+=500;
}
else if(s[i]=='M')
{
if(s[i-1]=='C' && i-1>=0)
{ result+=900;
i--;
}
else
result+=1000;
}
}
return result;
}
};