题目链接:https://leetcode.com/problems/roman-to-integer/
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
int Digit(char ch) {
int ret;
switch(ch) {
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;
}
}
int romanToInt(char* s) {
int ret = 0;
int i = strlen(s) - 1;
if(i >= 0)
ret = Digit(s[i]);
for(i = strlen(s) - 2; i >= 0; --i) { //从数组后向前遍历
if(Digit(s[i]) < Digit(s[i + 1]))
ret -= Digit(s[i]);
else
ret += Digit(s[i]);
}
return ret;
}
本文介绍了一种将罗马数字转换为整数的算法实现。通过解析罗马数字的构成规律,利用字符映射表获取每个字符对应的数值,并通过前后字符大小比较完成最终整数的计算。
139

被折叠的 条评论
为什么被折叠?



