Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution:
Process each char one time, for 'M','D','L','V' add the corresponding numbers. For'C','X','I' check the next char, if next char is corresponded with a larger number,add the current number, otherwise subtract it. For example the current char is 'I', if next one is 'V' or 'X', which means the current 'I' is part of 4 or 9, so we need to subtract 1 and then add 5, or 9 for next char.
public int romanToInt(String s) {
if(s==null || s.length()==0) return 0;
int res=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='M') res+=1000;
else if(s.charAt(i)=='D') res+=500;
else if(s.charAt(i)=='C'){
if(i+1<s.length() && (s.charAt(i+1)=='D' || s.charAt(i+1)=='M')) res-=100;
else res+=100;
}
else if(s.charAt(i)=='L') res+=50;
else if(s.charAt(i)=='X'){
if(i+1<s.length() && (s.charAt(i+1)=='L' || s.charAt(i+1)=='C')) res-=10;
else res+=10;
}
else if(s.charAt(i)=='V') res+=5;
else if(s.charAt(i)=='I'){
if(i+1<s.length() && (s.charAt(i+1)=='V' || s.charAt(i+1)=='X')) res-=1;
else res+=1;
}
else return 0;
}
return res;
}
No comments:
Post a Comment