Last active
April 25, 2016 09:56
-
-
Save nesterchung/70931591bc12e0676e71613ad9132c39 to your computer and use it in GitHub Desktop.
roman to int
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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