<p>
13. Roman to Integer
Total Accepted: 94716
Total Submissions: 231835
Difficulty: Easy
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
</p>
<code>
public class RmanToInteger13 {
public int romanToInt(String s) {
char[] cArr = s.toCharArray();
int value=0;
char max = 'I';
for(int i=cArr.length-1;i>=0;--i){
if(getValue(cArr[i])>=getValue(max)){
value+=getValue(cArr[i]);
max = cArr[i];
}else{
value-=getValue(cArr[i]);
}
}
return value;
}
//I V X L C D M;
private int getValue(char c){
int v=0;
switch(c){
case 'I': v=1;break;
case 'V': v=5;break;
case 'X': v=10;break;
case 'L': v=50;break;
case 'C': v=100;break;
case 'D': v=500;break;
case 'M': v=1000;break;
}
return v;
}
public static void main(String[] args){
String str= "DCXXI";//621
RmanToInteger13 rti = new RmanToInteger13();
System.out.println(rti.romanToInt(str));
}
}
</code>