一、题目描述
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题目解读:将罗马数字转化为对应的整数
I II III IV V VI VII VIII IX X
1 2 3 4 5 6 7 8 9 10
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
思路:设置三个标志,比如IV是4 , IX是9,XL是40,CD是400,CM是900
所以当出现I,X,C时要标记一下,在判断下一个字符的时候要将这三个是否出现在前面考虑进来。
c++代码(36ms)
class Solution {
public:
int romanToInt(string s) {
int result = 0;
int len = s.length();
int flag1 = 0; //I的标记
int flag2 = 0; //X的标记
int flag3 = 0; //C的标记
for(int i=0; i<len; i++){
if(s[i] == 'I'){
result += 1;
flag1 = 1; //标记前一个是I
}
else if(s[i] == 'V'){ //5
if(flag1){
result += 3;
flag1 = 0;
}
else{
result += 5;
}
}
else if(s[i] == 'X'){ //10
if(flag1){
result += 8;
flag1 = 0;
}
else{
flag2 = 1;
result += 10;
}
}
else if(s[i] == 'L'){
if(flag2){
result += 30;
flag2 = 0;
}
else
result += 50;
}
else if(s[i] == 'C'){
if(flag2){
result += 80;
flag2 = 0;
}
else{
flag3 = 1;
result += 100;
}
}
else if(s[i] == 'D'){
if(flag3){
result += 300;
flag3 = 0;
}
else
result += 500;
}
else if(s[i] == 'M'){
if(flag3){
result += 800;
flag3 = 0;
}
else
result += 1000;
}
}
return result;
}
};
注意:
当出现错误
invalid conversion from ‘const char*’ to ‘const char&’ [-fpermissive]
时,将字符的" "改成' '(双引号改成单引号)即可。
其他代码,使用map存I,V,X,L,C,D,M的值
int romanToInt(string s)
{
unordered_map<char, int> T = { { 'I' , 1 },
{ 'V' , 5 },
{ 'X' , 10 },
{ 'L' , 50 },
{ 'C' , 100 },
{ 'D' , 500 },
{ 'M' , 1000 } };
int sum = T[s.back()];
for (int i = s.length() - 2; i >= 0; --i)
{
if (T[s[i]] < T[s[i + 1]])
{
sum -= T[s[i]];
}
else
{
sum += T[s[i]];
}
}
return sum;
}
int romanToInt(string s) {
if (s.empty()) return 0;
int roman[24] = {};
roman['I' - 'A'] = 1;
roman['V' - 'A'] = 5;
roman['X' - 'A'] = 10;
roman['L' - 'A'] = 50;
roman['C' - 'A'] = 100;
roman['D' - 'A'] = 500;
roman['M' - 'A'] = 1000;
auto sum = 0;
auto right = roman[s.front() - 'A'];
for (int i = 1; i < s.size(); ++i) {
auto curr = right;
right = roman[s[i] - 'A'];
if (right > curr)
sum -= curr;
else
sum += curr;
}
return sum + right;
}