BiruLyu
7/28/2017 - 11:29 PM

13. Roman to Integer(#).java

``````"""
Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.
"""
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
numerals = {
'M' : 1000,
'D' : 500,
'C' : 100,
'L' : 50,
'X' : 10,
'V' : 5,
'I' : 1

}

res = 0;
for i in range(len(s)):
res += numerals[s[i]];
if i > 0 and numerals[s[i]] > numerals[s[i-1]]:
res -= numerals[s[i-1]] * 2;
return res;``````
``````public class Solution {
public int romanToInt(String s) {
int nums[]=new int[s.length()];
for(int i=0; i<s.length(); i++){
switch (s.charAt(i)){
case 'M':
nums[i]=1000;
break;
case 'D':
nums[i]=500;
break;
case 'C':
nums[i]=100;
break;
case 'L':
nums[i]=50;
break;
case 'X' :
nums[i]=10;
break;
case 'V':
nums[i]=5;
break;
case 'I':
nums[i]=1;
break;
}
}
int sum=0;
for(int i=0; i<nums.length-1; i++){
if(nums[i] < nums[i+1])
sum-=nums[i];
else
sum+=nums[i];
}
return sum+nums[nums.length-1];
}
}``````
``````public class Solution {
public int romanToInt(String s) {
char[] sc = s.toCharArray();
int sum = 0;
for (int index = sc.length - 1; index >= 0; index--) {
if (sc[index] == 'I') {
sum += (sum < 5 ? 1 : -1);
} else if (sc[index] == 'V') {
sum += 5;
} else if (sc[index] == 'X') {
sum += (sum < 50 ? 10 : -10);
} else if (sc[index] == 'L') {
sum += 50;
} else if (sc[index] == 'C') {
sum += (sum < 500 ? 100 : -100);
} else if (sc[index] == 'D') {
sum += 500;
} else if (sc[index] == 'M') {
sum += 1000;
}
}
return sum;
}
}``````
``````public class Solution {
public int romanToInt(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>(){{
put('M', 1000);
put('D', 500);
put('C', 100);
put('L', 50);
put('X', 10);
put('V', 5);
put('I', 1);
}};
int sum = 0;
sum += map.get(s.charAt(0));
for(int i = 1; i < s.length(); i++){
sum += map.get(s.charAt(i));
if(map.get(s.charAt(i)) > map.get(s.charAt(i - 1)))
sum -= map.get(s.charAt(i - 1)) * 2;
}
return sum;
}
}``````