13. Roman to Integer
【思路】
- 按照字符罗马数字规则改变成数字就行;
int roman(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 sum = 0;
int len = s.length();
for(int i=0;i<len -1;i++)
{ int cur = roman(s[i]), next = roman(s[i+1]);
if(cur<next)
sum+=-cur;
else
sum+=cur;
}
sum += roman(s[len -1]); //最低位
return sum;
}
网友评论