Created
December 27, 2012 16:49
-
-
Save zac-xin/4389754 to your computer and use it in GitHub Desktop.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
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 { | |
char symbols[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'}; | |
int values[] = {1000, 500, 100, 50, 10, 5, 1}; | |
public int romanToInt(String s) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(s.length() == 0) | |
return 0; | |
s = s.toUpperCase(); | |
for(int i = 0; i < symbols.length; i++){ | |
int index = s.indexOf(symbols[i]); | |
if(index != -1){ | |
return values[i] - romanToInt(s.substring(0, index)) + romanToInt(s.substring(index + 1)); | |
} | |
} | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment