Skip to content

Instantly share code, notes, and snippets.

@nesterchung
Last active April 25, 2016 09:56
Show Gist options
  • Save nesterchung/70931591bc12e0676e71613ad9132c39 to your computer and use it in GitHub Desktop.
Save nesterchung/70931591bc12e0676e71613ad9132c39 to your computer and use it in GitHub Desktop.
roman to int
public class Solution {
private static final String seq = "IVXLCDM";
public int romanToInt(String s) {
if (null == s || s.length() == 0) {
return 0;
}
if (s.length() == 1) {
return code(s.charAt(0));
}
String s1 = s.substring(0,1);
String s2 = s.substring(1,s.length());
return romanToInt(s1, s2);
}
private int romanToInt(String s1, String s2) {
if (seq.indexOf(s1) < seq.indexOf(s2.charAt(0))) {
return romanToInt(s2) - code(s1.charAt(0));
} else {
return code(s1.charAt(0)) + romanToInt(s2);
}
}
private int code(char c) {
int tmp = 0;
switch(c) {
case 'I':
tmp = 1;
break;
case 'V':
tmp = 5;
break;
case 'X' :
tmp = 10;
break;
case 'L':
tmp = 50;
break;
case 'C':
tmp = 100;
break;
case 'D':
tmp = 500;
break;
case 'M':
tmp = 1000;
break;
}
return tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment