Question:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution:
public class Solution {
public int romanToInt(String s) {
int sum = 0;
s = "AA" + s;
int len = s.length();
int sub = 0;
for(int i = len-1; i>1; i--){
if(chartoInt(s.charAt(i)) == 0)
break;
sum += chartoInt(s.charAt(i));
if(chartoInt(s.charAt(i-1)) >= chartoInt(s.charAt(i))){
;
}
else{
sub += chartoInt(s.charAt(--i));
}
}
return sum-sub;
}
public int chartoInt(char c){
int i =0;
switch(c){
case 'I':
i = 1;
break;
case 'V':
i = 5;
break;
case 'X':
i = 10;
break;
case 'L':
i = 50;
break;
case 'C':
i = 100;
break;
case 'D':
i = 500;
break;
case 'M':
i = 1000;
break;
case 'A':
i=0;
break;
default:
break;
}
return i;
}
}