Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
public class Solution {
public int romanToInt(String s) {
int l=s.length();
if(l==0)return 0;
int m=s.indexOf("M");
if(m!=-1){
String front=s.substring(0,m);
String behind=s.substring(m+1);
return 1000-romanToInt(front)+romanToInt(behind);
}
int d=s.indexOf("D");
if(d!=-1){
String front=s.substring(0,d);
String behind=s.substring(d+1);
return 500-romanToInt(front)+romanToInt(behind);
}
int c=s.indexOf("C");
if(c!=-1){
String front=s.substring(0,c);
String behind=s.substring(c+1);
return 100-romanToInt(front)+romanToInt(behind);
}
d=s.indexOf("L");
if(d!=-1){
String front=s.substring(0,d);
String behind=s.substring(d+1);
return 50-romanToInt(front)+romanToInt(behind);
}
d=s.indexOf("X");
if(d!=-1){
String front=s.substring(0,d);
String behind=s.substring(d+1);
return 10-romanToInt(front)+romanToInt(behind);
}
d=s.indexOf("V");
if(d!=-1){
String front=s.substring(0,d);
String behind=s.substring(d+1);
return 5-romanToInt(front)+romanToInt(behind);
}
d=s.lastIndexOf("I");
if(d!=-1){
return d+1;
}
return 0;
}
}