题目
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路
代码
Python
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
sLen = len(s)
res = 0
for i in range(0,sLen):
if s[i] == 'M':
res += 1000
if s[i] == 'D':
res += 500
if s[i] == 'C':
if (i < sLen - 1) and (s[i+1] == 'D' or s[i+1] == 'M'):
res -= 100
else:
res += 100
if s[i] == 'L':
res += 50
if s[i] == 'X':
if (i < sLen - 1) and (s[i+1] == 'L' or s[i+1] == 'C'):
res -= 10
else:
res += 10
if s[i] == 'V':
res += 5
if s[i] == 'I':
if (i < sLen - 1) and (s[i+1] == 'V' or s[i+1] == 'X'):
res -= 1
else:
res += 1
return resJava
public class Solution {
public int romanToInt(String s) {
int sLen = s.length();
int res = 0;
for(int i = 0;i < sLen;i++){
switch(s.charAt(i)){
case 'M':res += 1000;break;
case 'D':res += 500;break;
case 'C':{
if ((i < sLen - 1) && (s.charAt(i+1) == 'D' || s.charAt(i+1) == 'M')) res -= 100;
else res += 100;
break;
}
case 'L':res += 50;break;
case 'X':{
if ((i < sLen - 1) && (s.charAt(i+1) == 'L' || s.charAt(i+1) == 'C')) res -= 10;
else res += 10;
break;
}
case 'V':res += 5;break;
case 'I':{
if ((i < sLen - 1) && (s.charAt(i+1) == 'V' || s.charAt(i+1) == 'X')) res -= 1;
else res += 1;
break;
}
}
}
return res;
}
}
1万+




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



