【题目概要】
13. Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: "III"
Output: 3
【思路分析】
- 根据情况分类,主要是在双字母配合时,优先级大于单字母
【代码示例】
int romanToInt(char * s){
int len = strlen(s);
int sum = 0;
for(int index=0; index<len; index++)
{
if(s[index] == 'V')
sum += 5;
if(s[index] == 'L')
sum += 50;
if(s[index] == 'D')
sum += 500;
if(s[index] == 'M')
sum += 1000;
if(s[index] == 'I')
{
//考虑下为什么+1不会超过字符串【】取值范围,最后一位是空'\0'
sum = (s[index+1] == 'V' || s[index+1] == 'X')?sum-1:sum+1;
}
if(s[index] == 'X')
{
sum = (s[index+1] == 'L' || s[index+1] == 'C')?sum-10:sum+10;
}
if(s[index] == 'C')
{
sum = (s[index+1] == 'D' || s[index+1] == 'M')?sum-100:sum+100;
}
}
return sum;
}
// 针对每一种可以组成双字母的首字母进行判断,不满足则加上原来本身的值
917

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



